Pure javascript method to wrap content in a div Pure javascript method to wrap content in a div javascript javascript

Pure javascript method to wrap content in a div


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;


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


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/