原文: http://zetcode.com/javascript/documentall/

Document.all教程展示了如何使用all属性选择 JavaScript 中的所有 HTML 元素。

Document.all

Document 的all属性返回一个以文档节点为根的HTMLAllCollection-它返回页面的全部内容。 该属性是只读的。

在我们的示例中,我们将使用 Ramda 库遍历返回的HTMLAllCollection。 有关更多信息,请参见 Ramda 教程

Document.all示例

下面的示例演示文档all属性的用法。

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
  8. </head>
  9. <body>
  10. <p>
  11. This is simple web document.
  12. </p>
  13. <script>
  14. let allTags = document.all;
  15. let nOfTags = R.length(R.keys(allTags));
  16. console.log(`There are ${nOfTags} tags in the document`);
  17. console.log('List of tags:');
  18. R.forEachObjIndexed((value, key) => {
  19. console.log(`${key}: ${value.localName}`);
  20. }, allTags);
  21. </script>
  22. </body>
  23. </html>

在文档中,我们显示元素的数量及其列表。

  1. <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

我们包括 Ramda 库。

  1. let allTags = document.all;

使用document.all获取所有标签。

  1. let nOfTags = R.length(R.keys(allTags));
  2. console.log(`There are ${nOfTags} tags in the document`);

我们计算标签的数量并将消息显示到控制台。

  1. R.forEachObjIndexed((value, key) => {
  2. console.log(`${key}: ${value.localName}`);
  3. }, allTags);

使用 Ramda 的forEachObjIndexed(),我们遍历集合并输出所有标签名称。

在本教程中,我们使用了文档的all属性。

您可能也对以下相关教程感兴趣: JavaScript queryselector教程Element.innerHtml教程JavaScript Lodash 教程JQuery 教程Ramda 教程使用 jQuery DatePicker