Wrapping a set of DOM elements using JavaScript

Posted below are a pure JavaScript version of jQuery's wrap and wrapAll methods. I can't guarantee they work exactly as they do in jQuery, but they do in fact work very similarly and should be able to accomplish the same tasks. They work with either a single HTMLElement or an array of them. I haven't tested to confirm, but they should both work in all modern browsers (and older ones to a certain extent).

Unlike the selected answer, these methods maintain the correct HTML structure by using insertBefore as well as appendChild.

wrap:

// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

See a working demo on jsFiddle.

wrapAll:

// Wrap an HTMLElement around another HTMLElement or an array of them.
HTMLElement.prototype.wrapAll = function(elms) {
    var el = elms.length ? elms[0] : elms;

    // Cache the current parent and sibling of the first element.
    var parent  = el.parentNode;
    var sibling = el.nextSibling;

    // Wrap the first element (is automatically removed from its
    // current parent).
    this.appendChild(el);

    // Wrap all other elements (if applicable). Each element is
    // automatically removed from its current parent and from the elms
    // array.
    while (elms.length) {
        this.appendChild(elms[0]);
    }

    // If the first element had a sibling, insert the wrapper before the
    // sibling to maintain the HTML structure; otherwise, just append it
    // to the parent.
    if (sibling) {
        parent.insertBefore(this, sibling);
    } else {
        parent.appendChild(this);
    }
};

See a working demo on jsFiddle.


You can do like this:

// create the container div
var dv = document.createElement('div');
// get all divs
var divs = document.getElementsByTagName('div');
// get the body element
var body = document.getElementsByTagName('body')[0];

// apply class to container div
dv.setAttribute('class', 'container');

// find out all those divs having class C
for(var i = 0; i < divs.length; i++)
{
   if (divs[i].getAttribute('class') === 'C')
   {
      // put the divs having class C inside container div
      dv.appendChild(divs[i]);
   }
}

// finally append the container div to body
body.appendChild(dv);

I arrived at this wrapAll function by starting with Kevin's answer and fixing the problems presented below as well as those mentioned in the comments below his answer.

  1. His function attempts to append the wrapper to the next sibling of the first node in the passed nodeList. That will be problematic if that node is also in the nodeList. To see this in action, remove all the text and other elements from between the first and second <li> in his wrapAll demo.
  2. Contrary to the claim, his function won't work if multiple nodes are passed in an array rather than a nodeList because of the looping technique used.

These are fixed below:

// Wrap wrapper around nodes
// Just pass a collection of nodes, and a wrapper element
function wrapAll(nodes, wrapper) {
    // Cache the current parent and previous sibling of the first node.
    var parent = nodes[0].parentNode;
    var previousSibling = nodes[0].previousSibling;

    // Place each node in wrapper.
    //  - If nodes is an array, we must increment the index we grab from 
    //    after each loop.
    //  - If nodes is a NodeList, each node is automatically removed from 
    //    the NodeList when it is removed from its parent with appendChild.
    for (var i = 0; nodes.length - i; wrapper.firstChild === nodes[0] && i++) {
        wrapper.appendChild(nodes[i]);
    }

    // Place the wrapper just after the cached previousSibling,
    // or if that is null, just before the first child.
    var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild;
    parent.insertBefore(wrapper, nextSibling);

    return wrapper;
}

See the Demo and GitHub Gist.


Here's my javascript version of wrap(). Shorter but you have to create the element before calling the function.

HTMLElement.prototype.wrap = function(wrapper){
  
  this.parentNode.insertBefore(wrapper, this);
  wrapper.appendChild(this);
}

function wrapDiv(){
  
  var wrapper = document.createElement('div'); // create the wrapper
  wrapper.style.background = "#0cf"; // add style if you want
  
  var element = document.getElementById('elementID'); // get element to wrap
  
  element.wrap(wrapper);
}
div {
  border: 2px solid #f00;
  margin-bottom: 10px;
}
<ul id="elementID">
  <li>Chair</li>
  <li>Sofa</li>
</ul>

<button onclick="wrapDiv()">Wrap the list</button>

If you're target browsers support it, the document.querySelectorAll uses CSS selectors:

var targets = document.querySelectorAll('.c'),
  head = document.querySelectorAll('body')[0],
  cont = document.createElement('div');
  cont.className = "container";
for (var x=0, y=targets.length; x<y; x++){
  con.appendChild(targets[x]);
}
head.appendChild(cont);