Remove Parent Element without removing Child using JS

avatar

Borislav Hadzhiev

Sat Jan 01 20222 min read

Remove Parent Element without removing Child using JS #

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 replaceWith method replaces the element with a set of Node objects.

Here is the HTML for the examples in this article.

index.html
<!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>

And here is the related JavaScript code.

index.js
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.

The replaceWith method takes a set of Node or DOMString objects 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.

This is needed because the replaceWith() method expects a list of comma-separated Node or DOMString objects.

The Node.childNodes property returns a NodeList containing the element's child nodes.

The child nodes include:

  • DOM elements
  • text nodes
  • comments

You might see people using the children property instead of childNodes, but they are different because children returns a collection of elements only, it doesn't include text nodes and comments.

If the element does not have any child nodes, the childNodes property would return an empty NodeList and 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.