Phillip Chan Phillip Chan - 6 months ago 18
HTML Question

How to remove wrapper of multiple elements without jquery?

I have a set of elements and want to remove its container wrapper in Javascript.

I've researched around (this, this, and this) but I need a solution that 1) doesn't involve jQuery. 2) and can work on multiple elements.

HTML:

<div class="global-container stacked">
<article class="global"></article>
<article class="global"></article>
</div>


I've tried:

var globalArticles = document.getElementsByClassName('global');
globalArticles.outerHTML = globalArticles.innerHTML;


But that doesn't work. How would one go about removing the wrapper from all
article.global
?

Answer

You could just create your own unwrap() method, something like this

function unwrap(elems) {
    elems = 'length' in elems ? elems : [elems];
    for (var i = 0; i < elems.length; i++) {
        var elem        = elems[i];
        var parent      = elem.parentNode;
        var grandparent = parent.parentNode;

        grandparent.insertBefore(elem, parent);

        if (parent.children.length === 0) 
            grandparent.removeChild(parent);
    }
}

var globalArticles = document.getElementsByClassName('global');    

unwrap(globalArticles);
Comments