Copying children elements of one division to another along with all associated events
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: ");
conso开发者_如何学编程le.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.
- the variable
temp
seems to be an alias forsb_button
: you could remove the variable declaration and replace all references withtemp
sb_button
is a confusing name for an arbitrary child node- you're appending the node in
sb_button
tonewparent
within the if statement, but right after you're trying to setsb_button_.parentNode
toparent
- that's not possible sinceparentNode
is readonly and it certainly doesn't make sense - you can't append the element to one element but have a different parent. - are you trying to copy or move nodes?
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 sort
to make it immediately obvious you're just rearranging things), and then make a function that takes a newparent
and the array and appends copies of all elements in array order to newparent
. 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.:
for(var child = parent.firstChild; child; child = child.nextSibling)
if(child.id == curr_button.id) { //insert prev_button after curr_button
newparent.appendChild(child.cloneNode(true));
newparent.appendChild(prev_button.cloneNode(true));
} else if(child.id != prev_button.id) {
newparent.appendChild(child.cloneNode(true));
}
parent.parentNode.replaceChild(newparent, parent);
The idea being to make it instantly obvious to the reader that all children are processed exactly once.
精彩评论