Click here to Skip to main content
15,879,326 members
Articles / Programming Languages / Javascript
Tip/Trick

Dropping a DOM Node Without Consulting Its Parent

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
12 Jul 2018CPOL1 min read 4.8K   1   1
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.

This article was originally posted at http://web-engineering.info/blog-feed.xml

License

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


Written By
Instructor / Trainer
Germany Germany
Researcher, developer, instructor and cat lover.

Co-Founder of web-engineering.info and the educational simulation website sim4edu.com.

Comments and Discussions

 
QuestionArticle...? Pin
User 1106097912-Jul-18 7:23
User 1106097912-Jul-18 7:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.