Dennis G
Dennis G

Reputation: 21788

Replace parent element with its contents

I'm trying to do something similar/same as in this question: How to remove only the parent element and not its child elements in JavaScript?

<div>
    This is some text here
    <h2>This is more text</h2>
</div>

All I want is to remove the H2 tag. The result should be:

<div>
    This is some text here
    This is more text
</div>

Assume that I have the H2 element already:

if (parentElement.nodeName.toLowerCase() == "h2") {
    //now what? I basically want to this: $.replaceWith(parentElement.innerText)
    //just without jQuery
}

Upvotes: 10

Views: 10313

Answers (3)

Gibolt
Gibolt

Reputation: 47127

Use modern JS!

const h2 = document.querySelector('h2');
h2.replaceWith(h2.firstChild);

To instead replace with all children, use:

h2.replaceWith(...h2.childNodes); // or h2.children, if you don't want textNodes

developer.mozilla.org

Can I Use - 96% Oct '22

Upvotes: 10

Hidde
Hidde

Reputation: 11931

First of all, get started on jQuery. It makes your life easier.

In jQuery, do the following:

var h2html = $('div h2').html();
$('div h2').remove();
$('div').append(h2html);

EDIT:

The above only works with 1 div and 1 h2 element, which is the last element in the div. It is just a quick example. Below is code that makes your life even more easier:

$('div h2').each(function (x, y) {
    $(this).replaceWith($(this).html());
});​

Upvotes: -1

David Thomas
David Thomas

Reputation: 253318

Assuming the variable h2 accurately references the h2 element you want to act upon, my first thoughts would be:

var h2 = document.getElementsByTagName('h2')[0],
    textnode = h2.firstChild;

h2.parentNode.insertBefore(textnode,h2.nextSibling);
h2.parentNode.removeChild(h2);​

JS Fiddle demo.

To make it slightly more DRY, a function approach could be:

function unwrapH2(el) {
    if (!el) {
        return false;
    }
    else {
        var textnode = el.firstChild,
            elParent = el.parentNode;

        elParent.insertBefore(textnode, h2.nextSibling);
        elParent.removeChild(h2);
    }
}

var h2 = document.getElementsByTagName('h2')[0];

unwrapH2(h2);

JS Fiddle demo.

Adjusted the above in response to Felix Kling's comments (below), and also to use replaceChild():

function unwrapH2(el) {
    if (!el) {
        return false;
    }
    else {
        var textnode = el.firstChild,
            elParent = el.parentNode;
        elParent.replaceChild(textnode,el);
    }
}

var h2 = document.getElementsByTagName('h2')[0];

unwrapH2(h2);

JS Fiddle demo.

Upvotes: 5

Related Questions