Reputation: 548
I'm trying to create a DIV and append it to all existing DIVs on the page with a for loop. The problem is while it's inside the for loop, it will add the new DIV only to the last found DIV and not to each one like the FOR loop is supposed to make it do. Can anybody tell me what I'm doing wrong?
Here's the code I'm working with:
HTML:
<div class="Id">
<div class="first">First</div>
</div>
<div class="Id">
<div class="first">First</div>
</div>
<div class="Id">
<div class="first">First</div>
</div>
<div class="Id">
<div class="first">First</div>
</div>
JS:
var secondDiv, secondDivImg, selectDivContainer;
secondDivImg = document.createElement("span");
secondDivImg.className = "divImg";
secondDiv = document.createElement("div");
secondDiv.className = 'second';
secondDiv.innerHTML = "Second";
secondDiv.appendChild(secondDivImg);
selectDivContainer = document.querySelectorAll('.Id');
var idLength = document.querySelectorAll('.Id').length;
for (var i=0; i<idLength; i++) {
selectDivContainer[i].appendChild(secondDiv);
console.log(i);
console.log(selectDivContainer[i]);
}
Here's a fiddle
I added a couple of console.log to see and they look like the right thing so I'm a little confused why this happens. Thanks!
Upvotes: 2
Views: 2563
Reputation: 27423
This is correct behavior.
The reason is the 2nd sentence of the MDN docs. After you add it the first time, the child you supply is a reference to an existing node, and then gets moved instead of copied.
From https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).
Upvotes: 2
Reputation: 574
You'll have to create multiple elements, since you can't append the same element to one document twice. That means your document.createElement()
call must be inside the loop.
var selectDivContainer = document.querySelectorAll('.Id');
var idLength = selectDivContainer.length;
var secondDiv, secondDivImg;
for (var i = 0; i < idLength; i++) {
secondDivImg = document.createElement("span");
secondDivImg.className = "divImg";
secondDiv = document.createElement("div");
secondDiv.className = "second";
secondDiv.innerHTML = "Second";
secondDiv.appendChild(secondDivImg);
selectDivContainer[i].appendChild(secondDiv);
}
EDIT:
Also, you may have noticed that I changed some parts of your code; for example, you should be consistent in quoting; do not use "
AND '
unless necessary (they are the same in JS). Also, for idLength
, your don't have to call document.querySelectorAll()
again.
Upvotes: 7