Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace parent element with its contents

Tags:

javascript

dom

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
}
like image 798
Dennis G Avatar asked Aug 17 '12 09:08

Dennis G


People also ask

How do you remove the parent element without removing a child?

To remove the parent element without removing its children, call the replaceWith() method on the parent element passing it the child nodes as a parameter, e.g. parent. replaceWith(... parent. childNodes) .

Which of the following method replaces the specified child element of the current element with a new element?

The Element. replaceChildren() method replaces the existing children of a Node with a specified new set of children.

What is the difference between parent element and parent node?

Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.


1 Answers

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 - 94% Apr 2020

like image 199
Gibolt Avatar answered Oct 16 '22 11:10

Gibolt