0

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?

Community
  • 1
  • 1
Phillip Chan
  • 993
  • 7
  • 17
  • Before you remove the `div` element, you'll need to move `article`s into the `div`'s parent. – mustaccio Jun 03 '16 at 22:58
  • an element cannot remove itself. the parent can remove a child. find `global` elements and put them inside the parent. then remove the container. http://stackoverflow.com/a/843681/1536309 – Blair Anderson Jun 03 '16 at 23:15
  • Which wrapper are you trying to remove? Your code would remove `
    ` wrappers, do you want to remove `
    `?
    – Barmar Jun 04 '16 at 00:32

3 Answers3

1

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);
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

You can use .innerHTML, .removeChild(), .insertAdjacentHTML()

var container = document.querySelector(".global-container");
var html = container.innerHTML; // store `html` of `container`
container.parentElement.removeChild(container); // remove `container`
document.body.insertAdjacentHTML("beforeend", html); // append `html`
<div class="global-container stacked">
    <article class="global">1</article>
    <article class="global">2</article>
</div>
guest271314
  • 1
  • 15
  • 104
  • 177
0

This should work:

var globalArticle = document.getElementsByClassName('global')[0];
if (globalArticle) {
    globalArticle.parentElement.outerHTML = globalArticle.parentElement.innerHTML;
}