tags:

views:

598

answers:

2

I have html code that looks roughly like this:

<div id="id1">
  <div id="id2">
    <p>some html</p>
    <span>maybe some more</span>
  </div>
  <div id="id3">
    <p>different text here</p>
    <input type="text">
    <span>maybe even a form item</span>
  </div>
</div>

Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:

<div id="id1">
  <div id="id3">...</div>
  <div id="id2">...</div>
</div>

Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?

+2  A: 

In this case, document.getElementById('id1').appendChild(document.getElementById('id2')); should do the trick.

More generally you can use insertBefore().

Greg
A: 

A bit cumbersome, but try this

var a = document.getElementById("id2").innerhtml;
var b = document.getElementById("id3").innerhtml;
document.getElementById("id2").innerhtml = b;
document.getElementById("id3").innerhtml = a;
document.getElementById("id2").id="a"
document.getElementById("id3").id="id2"
document.getElementById("a").id="id3"
trex279