“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 id="id3">
    <p>different text here</p>
    <input type="text">
    <span>maybe even a form item</span>

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>

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?

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

More generally you can use insertBefore().

This function takes any node that is passed into it and wraps it with the tag given. In the example code snippet I wrapped a span tag with a section tag.

function wrap(node, tag) {
  node.parentNode.insertBefore(document.createElement(tag), node);

function wrap(node, tag) {
  node.parentNode.insertBefore(document.createElement(tag), node);
let toWrap = document.querySelector("#hi");
wrap(toWrap, "section");
console.log(document.querySelector("section > #hi"), " section wrapped element");
<span id="hi">hello there!</span>

You can use
insertAdjacentElement instead of appendChild to have more control about the position of element with respect to a target element.

Syntax: targetElement.insertAdjacentElement(position, element).
It has four position codes as:

  • ‘beforebegin’: Before the targetElement itself.
  • ‘afterbegin’: Just inside the targetElement, before its first child.
  • ‘beforeend’: Just inside the targetElement, after its last child.
  • ‘afterend’: After the targetElement itself.

it appears as:


In your case, you can write the code as:

document.getElementById('id2').insertAdjacentElement('beforebegin', document.getElementById('id3'));

Note that this way, you don’t need reference the parent (container) element!

Also consider You have more elements than id2, id3, eg: id4, id5, id6. Now, if you want to reposition for example id5 after id2, its as simple as:

function changePosition() {
   document.getElementById('id2').insertAdjacentElement('afterend', document.getElementById('id5'));
<div id='container'>
  <div id='id1'>id1</div>
  <div id='id2'><u>id2</u></div>  
  <div id='id3'>id3</div>  
  <div id='id4'>id4</div>  
  <div id='id5'><b>id5</b></div>  
  <div id='id6'>id6</div>  

<p><input type="button" onclick="changePosition()" value="change position"></p>

Leave a Comment