...

View Full Version : "createElement" problem



ConfusedOfLife
08-26-2002, 10:19 PM
I saw a code that the scripter used v=createElement("div") for making a div in his document. Then he used

v.setAttribute("id","ourDiv")

for giving that an ID and then he used several commands, like v.style.backgroundcolor = "red" to change the div's style. I saw that code in a kind of big program, and when I tried to split that into seperate parts, I came up with the results that I think are reasonable, but the problem is that my program doesn't work! and his works! since I didn't know anything about this document.createElement("div"), did I have any mistake in writing the proper code or what? I write my complete code below that you see, but I actually said the whole thing above.


//---------------------------------------------------------------------------

<html>
<head>
<title>Untitled</title>
<script>
function makeDiv()
{
var v=document.createElement("div");
v.setAttribute("id","ourDiv");

v.style.position='relative';
v.style.left=100+'px';
v.style.top=100+'px';
v.style.width=200+'px';
v.style.height=200+'px';
v.style.backgroundColor="blue";
v.style.visibility='visible';
v.style.padding='0px 0px 0px 0px';

return v;
}
</script>
</head>

<body>
<script>
tt = new makeDiv();
tt.innerHTML = "salam";
</script>

</body>
</html>

Vladdy
08-26-2002, 10:28 PM
You need to append an element, created by document.createElement() to your document tree. Only then it becomes part of your document and is rendered (styles permitting).

For example if you want to append that div to the body of your document you need to do this:
document.body.appendChild(tt);

Also if you need to set more than one style attribute, define a style class
ttstyles
{
......
.......
}

and use the following command:

tt.className='ttstyles'

..or at least use the "with" statement:
with (v.style)
{ left='100px';
right='100px';
//and so on.....
}
- saves you some typing......

ConfusedOfLife
08-26-2002, 10:56 PM
Thank you vladdy, now it's working!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum