0

Let's say I have two <div> elements in the DOM. I can easily switch their markup between them with jQuery, like so:

function switch_html(el1, el2){
        var el1_content = el1.html();
        var el2_content = el2.html();
        el1.html(el2_content);
        el2.html(el1_content);
}

However, how do I actually switch the DOM elements, and not just copy & switch the HTML source? For example, in the app I am currently developing, I am swapping out <div> contents that include filled out <input> fields. If the source HTML of these fields is merely copied, then the values contained within the inputs will be lost.

Arash Milani
  • 6,149
  • 2
  • 41
  • 47
element119
  • 7,475
  • 8
  • 51
  • 74
  • 2
    jquery.replaceWith(). clone one node. replace the second into the first, then insert the clone where the second one was. that should clone the actual DOM stuff, not just the source, preserving any field values. – Marc B Dec 24 '12 at 03:50
  • take a look at [this answer](http://stackoverflow.com/questions/8034918/jquery-switch-elements-in-dom) – Arash Milani Dec 24 '12 at 03:51
  • @MarcB Like this: `var el3 = el1.clone();el1.replaceWith(el2);el2.replaceWith(el3);`? This seems to be just removing the first element. – element119 Dec 24 '12 at 04:01

2 Answers2

2

You can move the actual DOM nodes using jQuery append / element.appendChild. Move the actual DOM nodes, don't try to make copies/clones.

Try this:

var children1 = $('#el1').children();
var children2 = $('#el2').children();

$('#el1').append(children2);
$('#el2').append(children1);
Jack
  • 9,448
  • 3
  • 29
  • 33
0

javascript has a cloneNode() function which performs a "deep" clone when true is passed.

So:

 function switch_html(el1, el2){
      var el1Clone = el1.cloneNode(true);
      var el2Clone = el2.cloneNode(true);
      el2.replaceNode(el1Clone);
      el1.replaceNode(el2Clone);
 }

Or for a (slightly) more performant solution:

 function switch_html(el1, el2){
      var el2Clone = el2.cloneNode(true);
      el2.replaceNode(el1);
      el1.replaceNode(el2Clone);
 }

Please note, that the assumption here is you want to do this in raw JavaScript, ie: no jQuery

Abraham P
  • 15,029
  • 13
  • 58
  • 126