dmperkins74
dmperkins74

Reputation: 167

ID Divs in For Loops

Working in Javascript. I'm trying to duplicate a div and name it dynamically in a fo. Neither of the following appear to work:

var origDiv = document.getElementById("outerSquare");
for (i=1; i<=4; ++i){
    newDiv = document.body.appendChild(origDiv.cloneNode(true));
//  newDiv.id = "block"+i;
    newDiv.setAttribute("id", "block"+i);
}

Here's the Fiddle: http://jsfiddle.net/dmperkins74/5r01zyma/

Funny thing is, it appears to be only duplicating the div inside my "outerSquare". If I remove the attempt to reset the ID, it all fails. Any insights would be appreciated.

Thanks, Dan P.

Upvotes: 1

Views: 45

Answers (1)

sinisake
sinisake

Reputation: 11318

Use classes:

<div class="outerSquare">
<div class="innerSquare"></div>
</div>

var origDiv = document.getElementsByClassName("outerSquare")[0];

for (i=1; i<=4; ++i){
    newDiv = document.body.appendChild(origDiv.cloneNode(true));
    newDiv.style.left = i*40 +"px";
    newDiv.style.top = i*40 +"px";
//  newDiv.id = "block"+i;
   //newDiv.setAttribute("id", "block"+i);
}

origDiv.style.left = "200px";

block2.style.left = "400px";

http://jsfiddle.net/5r01zyma/3/ No id duplication, no styling problems.

By changing ID, you can't apply old css styles. That was problem. P.S. Now you can add id's if you need it.

Upvotes: 1

Related Questions