Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Dropping a DOM Node Without Consulting Its Parent

5.00/5 (1 vote)
12 Jul 2018CPOL1 min read 5.1K  
How to drop a DOM node without consulting its parent

For quite a long time, it was pretty cumbersome to delete a node from the DOM of an HTML document because one had to go to its parent and ask it to destroy its child (by invoking removeChild), like so:

JavaScript
var elemToDrop = document.getElementById("elemID");
elemToDrop.parentNode.removeChild( elemToDrop);

It has always felt strange having to use such an indirect approach (having to ask the parent) for the very basic operation of dropping a DOM node.

In its quest to fill the gaps of W3C's DOM Level 3, the WHAT working group has defined a new remove operation in its DOM Living Standard. Consider the following code, which is simpler and much more readable:

JavaScript
var elemToDrop = document.getElementById("elemID");
elemToDrop.remove();

According to Can I use, the new approach is available in all current browser versions (except Internet Explorer and Opera Mini). The good news is that by including a simple polyfill in your code, you can use the new approach also for older browser versions.

The browser support for the new remove operation is quite recent: only in April/May 2018 Edge, Firefox and Safari started supporting it.

Many tutorials on the Web still recommend using the obsolete indirect approach. For instance, w3schools.com (on July 12, 2018) still say:

It would be nice to be able to remove an element without referring to the parent. But sorry. The DOM needs to know both the element you want to remove, and its parent.

... instead of recommending the new approach, together with its polyfill.

Read more about modern web engineering on web-engineering.info.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)