Element: attributes 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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

浏览器兼容性

另见