Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does removeChild need a parent node?

After answering this question I am left wondering why removeChild needs a parent element. After all, we could simply do

node.parentNode.removeChild(node);

As the parent node should be always directly available to the Javascript/DOM engine, it is not strictly necessary to supply the parent node of the node that is to be removed.

Of course I understand the principle that removeChild is a method of a DOM node, but why doesn't something like document.removeNode exist (that merely accepts an arbitrary node as parameter)?

EDIT: To be more clear, the question is: why does the JS engine need the parent node at all, if it already has the (unique) node that's to be removed?

like image 281
Marcel Korpel Avatar asked Aug 06 '10 09:08

Marcel Korpel


1 Answers

I think it keeps the design simple. A node may exist in isolation but the more interesting case is the DOM tree. With removeChild, the node to be removed must be a child of the node on which the method was called.

Getting a list of all children and doing a manual comparison against each is not that expensive an operation. However, searching all descendants for a node that is to be removed is indeed expensive.

Edit: In response to your update, a browser is simply implementing the DOM spec, which defines a removeChild method on Node. The spec, in my opinion, has to be unambiguous and free of assumptions. It is similar to Dependency Injection from that perspective. The DOM Core spec models a tree using building blocks such as Node, Element, etc. Adding a lone method such as removeNode somewhere in these building blocks means the method has implicit knowledge about its environment - that it may be a child of some node, and it should be removed from there if it is.

The task of w3 is to make a very robust API which makes most things possible. They shouldn't worry about syntactic sugar as that can always be written around the native APIs if they are well written.

like image 62
Anurag Avatar answered Oct 10 '22 17:10

Anurag