EasyBB
EasyBB

Reputation: 6574

Rearranging elements with a simple function

 function rearrange(x, y) {
    x.parentNode.replaceChild(x, y);
    x.parentNode.insertBefore(y,x); 
 }

If I do

var a = document.getElementsByClassName('btn-button-google')[0];
var b = document.getElementsByClassName('btn-button-doodle')[0];
rearrange(b,a);

I get the following error

NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.

Which I understand since a is in one html div and b is in another div, but I'm curious as how to fix this from happening. this works

rearrange(b.parentNode,a.parentNode);

Since they are in the same node.

Example HTML

<div class="container">
   <div class="group">
     <a href="" class="btn-button-bold"><a>
     <a href="" class="btn-button-italic"><a>
     <a href="" class="btn-button-strike"><a>
   </div>
   <div class="group">
     <a href="" class="btn-button-font"><a>
     <a href="" class="btn-button-ffamily"><a>
     <a href="" class="btn-button-google"><a>
   </div>
   <div class="group">
      <a href="" class="btn-button-smilies"><a>
     <a href="" class="btn-button-doodle"><a>
     <a href="" class="btn-button-source"><a>
   </div>
</div>

Upvotes: 1

Views: 92

Answers (1)

cookie monster
cookie monster

Reputation: 10972

The .replaceChild method accepts the replacement as the first argument and the child to be replaced as the second. You have them reversed, which is causing the error.

Furthermore, if the intent is to swap, you'll need to hold a reference to the original position of y, since once you move it, it'll be forgotten.

This will work for most cases:

var yPar = y.parentNode, ySib = y.nextSibling; 
x.parentNode.replaceChild(y, x); 
yPar.insertBefore(x, ySib);

Keep in mind, that there's an additional issue to consider. It won't be an issue as long as the two nodes have different parents, but if the share a parent, and are adjacent to each other, and the cached nextSibling is the same as x, then it'll have no effect. So you'll need to test for this if that may be a possibility, and handle that special case.

Upvotes: 2

Related Questions