Sat Jan 01 2022·2 min read
Photo by Jonathan Pendleton
To remove the parent element without removing its children, call the
replaceWith() method on the parent element passing it the child nodes as a
method replaces the element with a set of Node objects.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent" style="background-color: salmon"> <div>Child 1</div> <div>Child 2</div> <div>Child 3</div> </div> <script src="index.js"></script> </body> </html>
const parent = document.getElementById('parent'); parent.replaceWith(...parent.childNodes);
We used the
document.getElementById() method to select the parent element.
We then called the replaceWith method to replace the parent element with its child nodes.
replaceWithmethod takes a set of
DOMStringobjects as parameters and replaces the element it was called on with the provided values.
Notice that we used the spread syntax (...) to unpack the
NodeList of child
nodes in the call to the
replaceWith()method expects a list of comma-separated
property returns a
NodeList containing the element's child nodes.
The child nodes include:
You might see people using the
property instead of
childNodes, but they are different because
returns a collection of elements only, it doesn't include text nodes and
childNodesproperty would return an empty
NodeListand we would just remove the element without replacing it with anything.
No error would be thrown, so we don't have to handle anything special in this scenario.