...

View Full Version : Creating child elements



SlowCoder
01-14-2012, 03:36 AM
I'm a true newbie when it comes to JavaScript. To learn the language, I've set up a project for myself, a sort of board game.

As it is, I have a series of divs, each with an image (img tag). The divs ids are "Space1", "Space2", "Space3", etc. I am trying to dynamically create child divs inside the space divs as player markers. Here is the code:



<script type="text/javascript">
for(intA=0;intA<=10;intA++){
var NewDiv=document.createElement("div")
NewDiv.setAttribute("id","Space"+intA+"Player1")
NewDiv.style.width="20px";NewDiv.style.height="20px"
NewDiv.style.position="relative"
NewDiv.style.left="10px";NewDiv.style.top="10px"
NewDiv.innerHTML="1"
NewDiv.style.backgroundColor="#333333"
NewDiv.style.border="2px solid black"
NewDiv.style.visibility="visible"
NewDiv.style.zIndex="1000"
document.getElementById("Space"+intA).appendChild(NewDiv)
}
</script>


The assumption is that this code should make a 20x20 gray box with a "1" in it. I've tried playing with the visibility and the z-index, but nothing is showing up. What am I doing wrong here?

xelawho
01-14-2012, 03:57 AM
[EDIT]oops - sorry, I think I just got what you were trying to do... you understand that the loop starts at 0, right? So if you do not have a div with ID "Space0" the code will fail on the first run. If that's the problem you can either make a "Space0" div or else start the loop from 1 like this:

for(intA=1;intA<=11;intA++){

SlowCoder
01-14-2012, 04:09 AM
I think your biggest problem was that you were trying to append the div to itself.



Mine: document.getElementById("Space"+intA).appendChild(NewDiv)
Yours: document.body.appendChild(NewDiv)

Won't your code attach the dynamically created div to the document/body, rather than the intended parent div ("SpaceX")?

Can you explain how you mean I was trying to append the div to itself?

xelawho
01-14-2012, 04:14 AM
yes you are correct - please see my edited post above

xelawho
01-14-2012, 04:21 AM
and another thing I just noticed - the <= in the loop will only cause you grief. better to write it like this:


for(intA=1;intA<11;intA++){



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum