1

Say I have two node references in variables nodeA and nodeB. I would like to mutually replace them with each other in DOM, keeping their all attributes and attached event handlers etc.

How can I accomplish this with jQuery? I tried .replaceWith(...) but as I see it works with html text, and I would like to keep the DOM object itself.

There will be two .replaceWith(...) call. And the second one is on a node, which is not in the DOM... It seems not working...

Thanks in advance

g.pickardou
  • 32,346
  • 36
  • 123
  • 268

2 Answers2

1

It will be simmilar as switch variables, but you need to think it in terms of DOM.

var temp = $('<div>'); 
temp.insertAfter(first);
first.insertAfter(second);
second.insertAfter(temp);
temp.remove();

JS Fiddle: http://jsfiddle.net/qsutQ/

hazzik
  • 13,019
  • 9
  • 47
  • 86
1

Using a function from this answer:

jquery: switch Elements in DOM

function swapElements(elm1, elm2) {
    var parent1, next1,
        parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}

Switching should be pretty simple and doesn't require creating any temporary elements:

swapElements($("#obj1")[0], $("#obj2")[0]);

Fiddle:
http://jsfiddle.net/JvAMq/1/
(Click on the text to see alert boxes, the event bindings hold)

Community
  • 1
  • 1
Jace
  • 3,052
  • 2
  • 22
  • 33