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

瀏覽器相容性

另見