Element: attributes 属性
Element.attributes 属性返回一个指定节点上所有已注册属性节点的实时集合。它是一个 NamedNodeMap,而不是一个 Array,因此它没有 Array 方法,并且 Attr 节点的索引在不同浏览器之间可能不同。更具体地说,attributes 是一个字符串的键/值对,代表有关该属性的任何信息。
值
一个 NamedNodeMap 对象。
示例
基本示例
js
// Get the first <p> element in the document
const paragraph = document.querySelector("p");
const attributes = paragraph.attributes;
枚举元素的属性
您可以使用 for...of 循环遍历元素的属性。以下示例将遍历文档中 id 为 "paragraph" 的元素的属性节点,并打印每个属性的值。
html
<p id="paragraph" class="green" contenteditable>Sample Paragraph</p>
<input type="button" value="Show paragraph attribute name and value" />
<pre id="result"></pre>
css
.green {
color: green;
}
js
const paragraph = document.getElementById("paragraph");
const result = document.getElementById("result");
const btn = document.querySelector("input[type='button']");
btn.addEventListener("click", () => {
// First, let's verify that the paragraph has some attributes
if (paragraph.hasAttributes()) {
let output = "Attributes of first paragraph:\n";
for (const attr of paragraph.attributes) {
output += `${attr.name} -> ${attr.value}\n`;
}
result.textContent = output;
} else {
result.textContent = "No attributes to show";
}
});
规范
| 规范 |
|---|
| DOM # dom-element-attributes |
浏览器兼容性
加载中…
另见
NamedNodeMap,返回对象的接口- 跨浏览器兼容性注意事项:关于 quirksmode