I am trying to replace a certain div element parent with another one newparent. I want to copy only some of parent‘s children and put them in newparent, and then replace the parent by newparent.
Here is a snippet of my code:
var sb_button = parent.firstChild;
var temp;
while(sb_button) {
console.log("loop: ");
console.log(sb_button.id);
temp = sb_button;
if(sb_button.id != curr_button.id && sb_button.id != prev_button.id) {
console.log("if");
newparent.appendChild(temp);
}
else if(sb_button.id == curr_button.id) {
console.log("elseif");
newparent.appendChild(temp);
newparent.appendChild(prev_button);
}
else {
console.log("else");
}
sb_button.parentNode = parent;
console.log(sb_button.id)
console.log(sb_button.parentNode.children);
sb_button = sb_button.nextSibling;
}
parent.parentNode.replaceChild(newparent,parent);
EDIT :
So when I do newparent.appendChild(temp) it modifies sb_button. What’s the workaround for this?
I haven’t run your code, but there’s a few weird things, perhaps one of which may cause the issue or help clear up the code so the issue is more obvious.
tempseems to be an alias forsb_button: you could remove the variable declaration and replace all references withtempsb_buttonis a confusing name for an arbitrary child nodesb_buttontonewparentwithin the if statement, but right after you’re trying to setsb_button_.parentNodetoparent– that’s not possible sinceparentNodeis readonly and it certainly doesn’t make sense – you can’t append the element to one element but have a different parent.Edit: given that you want to copy nodes, I believe you’re looking for
cloneNode: make a copy of the node and append that copy, not the original node.As a matter of clean design, when things get complicated, I’d avoid this kind of hard-to-reason-about while loop. Instead, simply make an array of the nodes, order those the way you want (you could even do this using
sortto make it immediately obvious you’re just rearranging things), and then make a function that takes anewparentand the array and appends copies of all elements in array order tonewparent. Your example isn’t that complex, but even here, I’d change the order of the if-clauses to have the “default” case in the final else. e.g.:The idea being to make it instantly obvious to the reader that all children are processed exactly once.