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
  • 28,328
  • 32
  • 103
  • 221
  • 1
    `replaceWith` works fine with jQuery objects too. – Jon Apr 18 '13 at 08:54
  • `replaceWith` is correct. It will remove them from the DOM and insert the new content in its place with a single call. – mattytommo Apr 18 '13 at 08:55
  • 1
    There will be two .replaceWith(...) call. And the second one is on a node, which is not in the DOM... – g.pickardou Apr 18 '13 at 08:57
  • possible duplicate of [jquery: switch Elements in DOM](http://stackoverflow.com/questions/8034918/jquery-switch-elements-in-dom) – hazzik Apr 18 '13 at 09:13

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
  • 12,584
  • 7
  • 43
  • 85
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,022
  • 2
  • 20
  • 33