Wrapping a set of DOM elements using JavaScript

jquery wrap multiple elements in div
jquery wrap div around every 3 elements
javascript wrap text in span
javascript wrap element in anchor
jquery wrap not working
javascript wrap text in element
javascript wrap image in div
insertbefore

I have a series of p tags on my page and I want to wrap them all into a container, e.g.

<p>foo</p>
<p>bar</p>
<p>baz</p>

I want to wrap all the above tags into a container as follows:

<div>
    <p>foo</p>
    <p>bar</p>
    <p>baz</p>
</div>

How to wrap a NodeList in an element using vanilla JavaScript?

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);

Wrap an HTML structure around an element, How to use a given container as wrapper for another DOM element. Wrap a given element in a new container element using plain JavaScript: // element that will be � Create a new element with the DOM How to use document.createElement() to create an element, and wrap it around each selected element. Wrap elements using a function Using a function to specify what to wrap around each selected element. Wrap and unwrap an element How to toggle between wrapping and unwrapping an element.

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.

HTML DOM Style flexWrap Property, Definition and Usage. The flexWrap property specifies whether the flexible items should wrap or not. Note: If the elements are not flexible items, the flexWrap� Wrap a given element in a new container element using plain JavaScript: // element that will be wrapped var el = document.querySelector('div.wrap_me'); // create wrapper container var wrapper = document.createElement('div'); // insert wrapper before el in the DOM tree el.parentNode.insertBefore(wrapper, el); // move el into wrapper wrapper

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.

jQuery wrap() Method, DOM elements. function(index), Optional. Specifies a function that returns the wrapping element. index - Returns the index position of the element in the set� The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements.

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>

.wrap(), wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

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);

.wrapAll(), Description: Wrap an HTML structure around all elements in the set of matched elements. A selector, element, HTML string, or jQuery object specifying the structure to wrap <script src="https://code.jquery.com/jquery-3.5.0.js"></script>. Finding HTML Elements by CSS Selectors. If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

5 datchley / dom-utils.js, DOM related utilities, implementations for wrap(), wrapAll(), geStyle() and dom- utils.js. /** Faster Wrap an HTMLElement around another set of elements. JavaScript DOM Selectors. In this tutorial you will learn how to select DOM elements in JavaScript. Selecting DOM Elements in JavaScript. JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc.

Selection and Range, Then we can set the selection boundaries using range. Here's its DOM structure, note that here text nodes are important for us: at the beginning of the range; surroundContents(node) – wrap node around range content. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

JavaScript best practices, It is easier to wrap the whole thing in an anonymous function and protect the to create everything you need in a document using JavaScript and the DOM it is not to use JavaScript to set a class on a parent element and use syntax along the� I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_"). How can I achieve this using JavaScript? If needed, for simplicity, I can assume that all elements inside the div are of type input or select.

Comments
  • Good answer, but one nitpick/question - document.body is supported in every browser and is surely more efficient that searching the DOM for all instances of body and selecting by array index?
  • @lucideer: That's true probably but i just went with convention :)
  • @lucideer: "document.body... is surely more efficient" PREMATURE OPTIMISATION, I want to see screenshots of your benchmarks of document.body versus document.getElementsByTagName('body') in all modern browsers IMMEDIATELY :)
  • @KatieK Technically you should need to run removeChild first here, but running appendChild on an element that's already in DOM triggers an explicit removeChild call first (the spec. says all browsers should do this, and all do afaik).
  • One issue with this script that I’ve just noticed (18 months later) is that it won’t wrap the existing <div>s in-place: it’ll remove them from wherever they are in the document, put them into the container <div>, then append the container <div> to the end of the document (which isn’t necessarily where the <div>s were originally). That may be the desired behaviour, but I thought I’d point it out.
  • Just as a heads up, you're better off not extending the prototype of HTMLElement as this could easily be unsafe and cause some major headaches (I believe it does if you're using jQuery). Use this as a global function instead.
  • Great code! Just a though: I think the last if statement is redundant, because if sibling is null/undefined, parent.insertBefore(this, sibling) should be doing exactly the same as parent.appendChild(this).
  • Fantastic solution. For versatility, how would I change this to accept a single node instead of a node list? It trips up at nodes[0].parentNode;.
  • @jkupczak The first argument must be an indexed collection of nodes. You could simply put your node in an array: wrapAll(nodes[0].parentNode, wrapper);
  • Eh, wasn't there also getElementsByClassName()? :)
  • nice solution! you have a typo on line 6 though. change con to cont