JavaScript中儿童和儿童诺德斯有什么区别?
我发现自己正在使用JavaScript,并且跨过 childnodes
和 children
属性。我想知道它们之间的区别是什么。另一个比另一个更喜欢吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我发现自己正在使用JavaScript,并且跨过 childnodes
和 children
属性。我想知道它们之间的区别是什么。另一个比另一个更喜欢吗?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
了解
.children
是 element 的属性。 1 只有元素具有
.Children
,而这些孩子都是类型元素。 2但是,
.childnodes < /code>
是 node 的属性。
.childnodes
可以包含任何节点。 3一个具体的示例是:
大多数情况下,您要使用
.Children
,因为通常您不想循环 text 或评论您的DOM操纵中的节点。如果您确实想操纵文本节点,则可能需要
。 textcontent
或 而不是。 4在确定要使用哪个之前,了解2之间的区别很重要:
.textContent
属性代表节点的文本内容及其后代< /strong>.NodeValue
属性代表当前节点的值。1。从技术上讲,它是 parentnode 的属性。
。请参阅差异此处或在这里。
2。它们都是元素,因为
.Children
是 htmlCollection 它只能包含元素。3。同样,
.childnodes
可以保存任何节点,因为它是 noReferrer“> nodeList 。4。或
.innertext
.innertextUnderstand 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.Children
仅返回 /strong>孩子,而node> node.childnodes
返回所有节点儿童。请注意,元素是节点,因此两者都可以在元素上找到。
我相信
childnodes
更可靠。例如,MDC(上面链接)指出,IE仅在IE 9中获得儿童
。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
:yourlement.nodetype
这将为您提供一个整数:(从<<<<<< a href =“ https://developer.mozilla.org/en-us/docs/web/api/node/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: