views:

127

answers:

1

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?

+2  A: 

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.

Anurag
+1 That is better/correct explanation i think.
Sarfraz
Just one more side note: Diego Perini [said](http://twitter.com/diegoperini/status/20580063920) that IE and Opera actually support a [`removeNode`](http://msdn.microsoft.com/en-us/library/ms536708%28VS.85%29.aspx) method.
Marcel Korpel