Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending child div to each div with for loop

I want to append child div to each given parent divs. The child div supposed to be decorated by calling decorateDiv().

For example, after the appendChildren is executed, following divs should take the following form (assuming decorateDiv does nothing)

function appendChildren() 
{
var allDivs = document.getElementsByTagName("div");

for (var i = 0; i < allDivs.length; i++) 
  {
   var newDiv = document.createElement("div");
   decorateDiv(newDiv);
   allDivs[i].appendChild(newDiv);
  }
}

// Mock of decorateDiv function for testing purposes
function decorateDiv(div) {}

what am i doing wrong?

like image 841
Shaonline Avatar asked Dec 18 '25 17:12

Shaonline


2 Answers

You're running into the fact that .getElementsByTagName() returns a live NodeList. That means that the new <div> elements that you're adding to the page become part of the list as soon as you do so.

What you can do is turn that NodeList into a plain array beforehand:

var allDivs = document.getElementsByTagName("div");
allDivs = [].slice.call(allDivs, 0);

Now using "allDivs" in the loop will just append your new elements into the ones that were there when you originally went looking for them.

like image 177
Pointy Avatar answered Dec 20 '25 06:12

Pointy


Using the allDivs.length in the condition field will accesses the length property each time the loop iterates. So declare a variable for the length outside the function and specify the variable name in the condition field.

function appendChildren() 
{
var allDivs = document.getElementsByTagName("div");
var len = allDivs.length;

for (var i = 0; i < len ; i++) 
  {
   var newDiv = document.createElement("div");
   decorateDiv(newDiv);
   allDivs[i].appendChild(newDiv);
  }
}

// Mock of decorateDiv function for testing purposes
function decorateDiv(div) {}
like image 35
Kumar Guru Avatar answered Dec 20 '25 08:12

Kumar Guru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!