Skip to content
Advertisement

Pure javascript method to wrap content in a div

I want to wrap all the nodes within the #slidesContainer div with JavaScript. I know it is easily done in jQuery, but I am interested in knowing how to do it with pure JS.

Here is the code:

<div id="slidesContainer">
    <div class="slide">slide 1</div>
    <div class="slide">slide 2</div>
    <div class="slide">slide 3</div>
    <div class="slide">slide 4</div>
</div>

I want to wrap the divs with a class of “slide” collectively within another div with id="slideInner".

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement