How to Wrap an Element Within a New Element Using Javascript

Here’s a simple way of wrapping an HTML fragment that exists in the DOM within another element, in this case a div: var wrapper = document.createElement(‘div’); wrapper.id = ‘the-wrapper’; wrapper.appendChild(document.querySelector(‘#the-html-fragment’)); At this point, the HTML fragment that was selected via the #the-html-fragment selector was removed from the DOM and attached …