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
}
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) .
The Element. replaceChildren() method replaces the existing children of a Node with a specified new set of children.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With