Reputation: 582
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??
Upvotes: 0
Views: 541
Reputation: 318182
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);
}
Upvotes: 3
Reputation: 2909
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.
Upvotes: 1