Pure javascript method to wrap content in a div

Viewed 130263

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".

10 Answers

How to "wrap content" and "preserve bound 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

A general good tip for trying to do something you'd normally do with jQuery, without jQuery, is to look at the jQuery source. What do they do? Well, they grab all the children, append them to a a new node, then append that node inside the parent.

Here's a simple little method to do precisely that:

const wrapAll = (target, wrapper = document.createElement('div')) => {
  ;[ ...target.childNodes ].forEach(child => wrapper.appendChild(child))
  target.appendChild(wrapper)
  return wrapper
}

And here's how you use it:

// wraps everything in a div named 'wrapper'
const wrapper = wrapAll(document.body) 

// wraps all the children of #some-list in a new ul tag
const newList = wrapAll(document.getElementById('some-list'), document.createElement('ul'))

To simply wrap a div without the need of the parent:

<div id="original">ORIGINAL</div>

<script>

document.getElementById('original').outerHTML
=
'<div id="wrap">'+
document.getElementById('original').outerHTML
+'</div>'

</script>

Working Example: https://jsfiddle.net/0v5eLo29/

More Practical Way:

const origEle = document.getElementById('original');
origEle.outerHTML = '<div id="wrap">' + origEle.outerHTML + '</div>';

Or by using only nodes:

let original = document.getElementById('original');
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.append(original.cloneNode(true));

original.replaceWith(wrapper);

Working Example: https://jsfiddle.net/wfhqak2t/

A simple way to do this would be:

let el = document.getElementById('slidesContainer');
el.innerHTML = `<div id='slideInner'>${el.innerHTML}</div>`;
Related