Pure javascript method to wrap content in a div

Solution 1:

If your "slide"s are always in slidesContainer you could do this

org_html = document.getElementById("slidesContainer").innerHTML;
new_html = "<div id='slidesInner'>" + org_html + "</div>";
document.getElementById("slidesContainer").innerHTML = new_html;

Solution 2:

Like BosWorth99, I also like to manipulate the dom elements directly, this helps maintain all of the node's attributes. However, I wanted to maintain the position of the element in the dom and not just append the end incase there were siblings. Here is what I did.

var wrap = function (toWrap, wrapper) {
    wrapper = wrapper || document.createElement('div');
    toWrap.parentNode.appendChild(wrapper);
    return wrapper.appendChild(toWrap);
};

Solution 3:

I think here is very good code example - this solution preserves binded events

// 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.appendChild(el);

or

function wrap(el, wrapper) {
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
}
// example: wrapping an anchor with class "wrap_me" into a new div element
wrap(document.querySelector('div.wrap_me'), document.createElement('div'));

ref

https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28/

Solution 4:

If you patch up document.getElementsByClassName for IE, you can do something like:

var addedToDocument = false;
var wrapper = document.createElement("div");
wrapper.id = "slideInner";
var nodesToWrap = document.getElementsByClassName("slide");
for (var index = 0; index < nodesToWrap.length; index++) {
    var node = nodesToWrap[index];
    if (! addedToDocument) {
        node.parentNode.insertBefore(wrapper, node);
        addedToDocument = true;
    }
    node.parentNode.removeChild(node);
    wrapper.appendChild(node);
}

Example: http://jsfiddle.net/GkEVm/2/

Solution 5:

I like to manipulate dom elements directly - createElement, appendChild, removeChild etc. as opposed to the injection of strings as element.innerHTML. That strategy does work, but I think the native browser methods are more direct. Additionally, they returns a new node's value, saving you from another unnecessary getElementById call.

This is really simple, and would need to be attached to some type of event to make any use of.

wrap();
function wrap() {
    var newDiv = document.createElement('div');
    newDiv.setAttribute("id", "slideInner");
    document.getElementById('wrapper').appendChild(newDiv);
    newDiv.appendChild(document.getElementById('slides'));
}

jsFiddle

Maybe that helps your understanding of this issue with vanilla js.