Skip to main content

HTML wrap element method written in pure JavaScript that works similarly to that in jQuery.

/**
 * This sample demonstrates a `wrap` method written in pure JavaScript
 * that works similarly to that in jQuery.
 *
 * If all text in the result window have red backgrounds, it worked!
 *
 * Answers this Stack Overflow question:
 * http://bit.ly/pure-js-wrap
 *
 * Live Example: 
 * http://jsfiddle.net/EV3J5/
 */

/*
 * 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);
        }
    }
};

//
// Example
//

var message = document.getElementById('message');
var div = document.createElement('div');
div.wrap(message);

var fruits = document.getElementsByTagName('li');
var ol = document.createElement('ol');
ol.wrap(fruits);