Search code examples
javascriptdom

"Cut and Paste" - moving nodes in the DOM with Javascript


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?


Solution

  • In this case

    document.getElementById('id1').appendChild(document.getElementById('id2'));

    should do the trick.
    More generally you can use insertBefore().