JavaScript 中的 child 和 childNode 有什么区别?
我发现自己使用 JavaScript,并且遇到了 childNodes
和 children
属性。我想知道它们之间有什么区别。还有一个比另一个更受青睐吗?
I have found myself using JavaScript and I ran across childNodes
and children
properties. I am wondering what the difference between them is. Also is one preferred to the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
了解
.children
是元素的属性。 1 只有Elements才有.children
,并且这些children都是Element类型。 2但是,
.childNodes< /code>
是 Node 的属性。
.childNodes
可以包含任何节点。 3一个具体的例子是:
大多数时候,您想要使用
.children
因为通常您不想循环 文本 或 注释节点DOM 操作。如果您确实想操作文本节点,您可能需要
。 textContent
或.nodeValue
相反。 4在决定使用哪一个之前,了解两者之间的区别非常重要:
.textContent
属性表示节点及其后代<的文本内容< /strong> 而.nodeValue
属性表示当前节点的值。1.从技术上讲,它是 ParentNode 的一个属性,是 Element 包含的 mixin。
2.它们都是元素,因为
.children
是一个 HTMLCollection,只能包含元素。3.同样,
.childNodes
可以保存任何节点,因为它是一个 NodeList.4.或者
.innerText
。请参阅此处或此处。Understand that
.children
is a property of an Element. 1 Only Elements have.children
, and these children are all of type Element. 2However,
.childNodes
is a property of Node..childNodes
can contain any node. 3A concrete example would be:
Most of the time, you want to use
.children
because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.If you do want to manipulate Text nodes, you probably want
.textContent
or.nodeValue
instead. 4It's important to understand the distinction between the 2, before deciding which one to use: The
.textContent
property represents the text content of the node and its descendants whereas the.nodeValue
property represents the value of the current node.1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because
.children
is a HTMLCollection, which can only contain elements.3. Similarly,
.childNodes
can hold any node because it is a NodeList.4. Or
.innerText
. See the differences here or here.Element.children
仅返回元素< /strong> 子节点,而Node.childNodes
返回所有节点子节点。请注意,元素是节点,因此两者都可用于元素。我相信
childNodes
更可靠。例如,MDC(上面链接)指出,IE 在 IE 9 中只获得了children
权限。childNodes
为浏览器实现者提供了更少的犯错空间。Element.children
returns only element children, whileNode.childNodes
returns all node children. Note that elements are nodes, so both are available on elements.I believe
childNodes
is more reliable. For example, MDC (linked above) notes that IE only gotchildren
right in IE 9.childNodes
provides less room for error by browser implementors.到目前为止,答案很好,我只想补充一点,您可以使用
nodeType
检查节点的类型:yourElement.nodeType
这将为您提供一个整数:(取自 < a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType" rel="noreferrer">此处)
请注意,根据 Mozilla:
Good answers so far, I want to only add that you could check the type of a node using
nodeType
:yourElement.nodeType
This will give you an integer: (taken from here)
Note that according to Mozilla: