Appendchild While Inside For Loop Doesn't Work Right
Solution 1:
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.
Solution 2:
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).
Post a Comment for "Appendchild While Inside For Loop Doesn't Work Right"