html - document.children VS document.childNodes

标签 html dom document w3c

接口(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/

相关文章:

html - Flexbox 拉伸(stretch)和对齐元素(在第二行和不同的屏幕上)

java - 如何获取 DOM 节点之前和之后的一些 xml

iframe - iframe 父级的 document.referrer

javascript - 渲染后如何替换 Angular 组件标签?

当有属性 block 时,jquery + div 不会用 .hide() 正确隐藏?

jquery - 删除输入字段的部分值

javascript - jQuery Cleditor 所见即所得文本编辑器 : keyup() works in webkit browsers but not Firefox or IE

javascript - 为什么源代码中看不到 DOM 结构?

ios - 对于 iOS 开发人员,我的应用程序如何知道对于给定的文件类型,其他应用程序可以打开它

javascript - Angular js单元测试mock文档