Search code examples
javascripthtmlappendchild

How to move All elements in the body with adding exception for some elements to not be moved?


I think the title is clear, but I've some examples for you guys, here is my idea:

I've this Html5:

<html>
<head></head>
<body class="oldParent">
<div class="p1"></div>
<div class="p2"></div>
<div class="p3"></div>
<div class="p4"></div>
<div class="p5"></div>
<div class="NewParent"></div>
</body>
</html>

as you can see my NewParent is child of My OldParent

(i want to move all body elements except NewParent), and i need to move all elements except this one:

<div class="**NewParent**"></div>

I'm New to Javascript and I thought that you guys know how to add exception for this, I've found this too:

var newParent = document.getElementById('NewParent');
        var oldParent = document.getElementById('OldParent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

but i don't know how to add exception!?

I need help:(


Solution

  • You're pretty close with your original code. Just switch to getElementsByClassName - but be aware it returns a collection so you'll have to index into it. You might want to switch to id's if that's an option.

    Then you can basically just add an if condition to test for the className of the element to exclude:

    var newParent = document.getElementsByClassName('NewParent')[0];
    var oldParent = document.getElementsByClassName('oldParent')[0];
    
    while (oldParent.childNodes.length > 0) {
      if (oldParent.childNodes[0].className !== 'NewParent') {
        newParent.appendChild(oldParent.childNodes[0]);
      }
      else { break; }
    }
    

    Here's a jsfiddle you can play with. Be careful with your class names, the ones for old and new parents have different casing.

    I would add while this is closest to your original code, it may not actually be the best way to solve this. This assumes your new parent is the last in the collection as it has to break out of your while loop due to the way you're looping. Cloning as the other answer shows is probably a safer solution.