Question

I have a real newbie question for you all:

I have this for loop:

var pNewTag = document.createElement('p');
var grabWrapper = document.querySelector('.footerInfo');
var myArray = grabWrapper.children;

 for ( var i = 0; i < myArray.length; i++ ) {
   grabWrapper.children[i].appendChild(pNewTag);
   pNewTag.innerHTML = " this works ";
 }

The array I'm working with has a length of 7, but the loop only does appendChild one time. I'd like it to function on every iteration. What am I missing??

Was it helpful?

Solution

That's because you only have one element, and you keep moving it around, you have to create one element for each iteration

var grabWrapper = document.querySelector('.footerInfo');
var myArray = grabWrapper.children;

for ( var i = 0; i < myArray.length; i++ ) {
   var pNewTag = document.createElement('p');
   pNewTag.innerHTML = " this works ";

   grabWrapper.children[i].appendChild(pNewTag);
}

OTHER TIPS

You have to create multiple p-elements:

var grabWrapper = document.querySelector('.footerInfo');
var myArray = grabWrapper.children;

for ( var i = 0; i < myArray.length; i++ ) {
    var pNewTag = document.createElement('p');
    pNewTag.innerHTML = " this works ";
    grabWrapper.children[i].appendChild(pNewTag);
}

Try to fill the element before adding it to the document. This way your browser does not have to reflow the document twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top