Document.all 教程
最后修改日期 2025 年 4 月 30 日
在本文中,我们将展示如何使用 all 属性在 JavaScript 中选择所有 HTML 元素。
Document.all
Document 对象的 all 属性返回一个 HTMLAllCollection,表示文档中的所有元素。它提供对整个页面内容的只读集合的访问。虽然此属性对于查询文档节点很有用,但它被认为是过时的,应谨慎使用,因为现代最佳实践建议使用其他 DOM 方法,例如 querySelector 或 getElementById 来选择元素。
在我们的示例中,我们将使用 Ramda 库遍历返回的 HTMLAllCollection。有关更多信息,请参阅 Ramda 教程。
Document.all 示例
以下示例演示了文档 all 属性的用法。
index.html
<!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,我们遍历集合并输出所有标签名称。
使用 JavaScript 突出显示段落
在本例中,我们演示了如何使用 JavaScript 动态突出显示网页中的所有 p 元素。 这是通过在单击按钮时切换段落元素上的 CSS 类来实现的。
highlight.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Highlight Paragraphs</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<h1>JavaScript Paragraph Highlighter</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>And this is the third paragraph.</p>
<button id="highlightBtn">Highlight All Paragraphs</button>
<script>
document.getElementById("highlightBtn").addEventListener("click", function() {
let paragraphs = document.querySelectorAll("p");
paragraphs.forEach(p => p.classList.toggle("highlight"));
});
</script>
</body>
</html>
该示例使用 querySelectorAll 方法选择所有 p 元素。 当单击按钮时,JavaScript 代码将 CSS 类 (.highlight) 应用于每个段落,更改其背景颜色和文本粗细。
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
.highlight CSS 类定义突出显示效果,使用黄色背景和粗体文本样式。
document.getElementById("highlightBtn").addEventListener("click", function() {
let paragraphs = document.querySelectorAll("p");
paragraphs.forEach(p => p.classList.toggle("highlight"));
});
这段 JavaScript 代码段 *向按钮添加一个事件侦听器*。 单击时,它选择所有 p 元素并切换突出显示类,有效地*打开和关闭*突出显示效果。
来源
在本文中,我们使用了文档的 all 属性。