接口(interface) Document继承接口(interface) Node并指定 Node.childNodes。它工作正常,但什么是 children?规范中没有这样的属性。
它们的工作方式不同。如果我们有 <!doctype html>
节点,document.childNodes 包含它,但 document.children 没有。
最佳答案
来自 Matthew Flaschen's answer :
Element.children returns only element children, while Node.childNodes returns all node children. Note that elements are nodes, so both are available on elements.
<!doctype html>
是一个节点是一个DOM树,所以它被列在childNodes
中, 但它是 a DocumentType node, not an Element , 所以它没有出现在 children
中.
找不到 children
的原因在您正在查看的规范中可能是因为它相对较新 - 它是在 DOM4 中添加的(仅在 2015 年成为 W3C 推荐标准)。
如果需要遍历Element
s 在 DOM 树中(忽略其他节点类型——例如文本节点),你会发现 children
和相关的API(first/lastElementChild, previous/nextElementSibling)更方便,但由于它们较新,旧浏览器并不普遍支持这些API,所以你应该引用compatibility tables和/或使用 polyfill。
关于html - document.children VS document.childNodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39288373/