JSFiddle - React, Tailwind, and code Playground
HTML
<!--
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
Authored by: Kevin Jurkowski, 11/02/2012
-->
<hr />
<p id="message">Hello, world!</p>
<hr />
<hr />
<li>Apples</li>
<hr />
<li>Bananas</li>
<li>Cherries</li>
<hr />
<li>Dates</li>
<hr />
CSS
hr { border: 1px solid #aaa; }
li { list-style-type: none; }
ol > li, div > p {
background: red;
}
JavaScript
// 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);
}
}
};
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);