Copying children of one section to another along with all related events

I am trying to replace some div element parentwith another newparent. I want to copy only some of the parentchildren and put them in newparent, and then replace them parentwith 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), he changes sb_button. What is the workaround for this?

+3
source share
1 answer

I do not run your code, but there are some strange things, maybe one of them can cause a problem or help clear the code so that the problem is more obvious.

  • temp sb_button: temp
  • sb_button - node
  • node sb_button newparent if, , sb_button_.parentNode parent - , parentNode readonly, , , - , .
  • ?

:, , , , cloneNode: node , node.

, , . , , ( sort, , ), , newparent newparent. , if-clauses, " " else. :.

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);

, , .

+4

All Articles