Dropping a DOM node without consulting its parent

gwagner's picture

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:

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:

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

According to Can I use, the new approach is available in all current browser versions (except IE 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.