How to Wrap an Element Within a New Element Using Javascript

Here’s a simple way of wrapping an HTML fragment that exists in the DOM within another element, in this case a div:

var wrapper = document.createElement('div');
wrapper.id = 'the-wrapper';
wrapper.appendChild(document.querySelector('#the-html-fragment'));

At this point, the HTML fragment that was selected via the #the-html-fragment selector was removed from the DOM and attached to the wrapper element in memory. You could then attach it back into the DOM in the following way (in this case, the body):

document.querySelector('body').appendChild(wrapper);

Attaching the newly wrapped element to the body typically would not be useful. If you want to put it back into the same position it originally was at, you’ll need to figure out a couple of things first. The first thing to figure out is to determine the wrapped element’s parent. You could do this by using the parentNode property (take a look at this article as an example):

var parent = document.querySelector('#the-html-fragment').parentNode;

The second thing you’ll need to figure out is what position that element is within the parentNode. One way to do this is to search for the element in the childNodes array:

var position = 0;
for(var i = 0; i < parent.childNodes.length; i++) {
  if(parent.childNodes[i] == document.querySelector('#the-html-fragment')) {
    position = i;
    break;
  };
};

So, let's put it all together!

var parent = document.querySelector('#the-html-fragment').parentNode;
var wrapper = document.createElement('div');
var position = 0;
for(var i = 0; i < parent.childNodes.length; i++) {
  if(parent.childNodes[i] == document.querySelector('#the-html-fragment')) {
    position = i;
    break;
  };
};
wrapper.id = 'the-wrapper';
wrapper.appendChild(document.querySelector('#the-html-fragment'));
parent.insertBefore(wrapper, parent.childNodes[position]);

Any comments/suggestions welcome, and happy coding!