Document.all 教程展示了如何使用 all
属性在 JavaScript 中选择所有 HTML 元素。
文档.all
Document 的all
属性返回以文档节点为根的HTMLAllCollection
——它返回页面的全部内容。该属性是只读的。
在我们的示例中,我们将使用 Ramda 库遍历返回的HTMLAllCollection
。有关详细信息,请参阅 Ramda 教程。
Document.all 示例
以下示例演示了文档的all
属性的用法。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> </head> <body> <p> This is simple web document. </p> <script> let allTags = document.all; let nOfTags = R.length(R.keys(allTags)); console.log(`There are ${nOfTags} tags in the document`); console.log('List of tags:'); R.forEachObjIndexed((value, key) => { console.log(`${key}: ${value.localName}`); }, allTags); </script> </body> </html>
在文档中,我们显示元素的数量及其列表。
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
我们包括 Ramda 库。
let allTags = document.all;
使用document.all
获取所有标签。
let nOfTags = R.length(R.keys(allTags)); console.log(`There are ${nOfTags} tags in the document`);
我们计算标签的数量并将消息显示到控制台。
R.forEachObjIndexed((value, key) => { console.log(`${key}: ${value.localName}`); }, allTags);
使用 Ramda 的forEachObjIndexed
,我们遍历集合并输出所有标签名称。
在本文中,我们使用了文档的 all
属性。
列出所有 JavaScript 教程。