Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...