为什么removeChild需要父节点? [英] Why does removeChild need a parent node?

查看:110
本文介绍了为什么removeChild需要父节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答此问题后,我不知道为什么 removeChild 需要一个父元素。毕竟,我们可以简单地做

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

node.parentNode.removeChild(node);

由于父节点始终可直接用于Javascript / DOM引擎,因此不是绝对必要的提供要删除的节点的父节点。

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.

当然,我理解 removeChild 是一个DOM节点的方法,但是为什么不存在像code> document.removeNode 这样的东西(只接受任意节点作为参数)?

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

编辑:更清楚的是,问题是:为什么JS引擎需要父节点,如果它已经具有(唯一)节点删除?

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?

推荐答案

我认为它保持设计简单。节点可能独立存在,但更有趣的情况是DOM树。使用 removeChild ,要删除的节点必须是调用该方法的节点的子节点。

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.

编辑:为了响应您的更新,浏览器是只需执行 DOM规范,其中定义了一个 removeChild 方法 Node 。我认为,的规范必须是明确的,没有假设。这与依赖注入相似。 DOM Core使用诸如Node,Element等构建块来模拟树。在这些构建块中的某个地方添加诸如 removeNode 的单独方法意味着该方法具有隐含的知识它的环境 - 它可能是某个节点的孩子,如果是,则应该从那里移除。

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.

w3的任务是制作一个非常强大的API,使大多数事情成为可能。他们不应该担心语法糖,因为它们总是可以写在本地API周围,如果它们写得很好。

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.

这篇关于为什么removeChild需要父节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆