MutationRecord: attributeName 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

MutationObserver 觀察到的節點的已更改屬性的名稱包含在只讀屬性 attributeName 中。

如果記錄的 typeattributes,則此屬性是表示突變目標突變屬性名稱的字串。

如果記錄的 type 不是 attributes,則此屬性為 null

示例

獲取最後一個更新的屬性名稱

在下面的示例中,有四個按鈕:兩個按鈕更改 h1 元素的 style 屬性,另外兩個按鈕更改 h1 元素的 class 屬性。指令碼使用 MutationObserver 來檢測更改,並將下面的文字更新為最後一個被更改的屬性的名稱。

HTML

html
<h1 class="blue" id="hiMom">Hi, Mom!</h1>

<button id="redButton">Set class to "red"</button>
<button id="blueButton">Set class to "blue"</button>
<button id="whiteButton">Set style to "color:white;"</button>
<button id="blackButton">Set style to "color:black;"</button>

<p id="log">Updated attribute name:</p>

CSS

css
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

JavaScript

js
const hiMom = document.querySelector("#hiMom");
const redButton = document.querySelector("#redButton");
const blueButton = document.querySelector("#blueButton ");
const whiteButton = document.querySelector("#whiteButton");
const blackButton = document.querySelector("#blackButton");
const log = document.querySelector("#log");

redButton.addEventListener("click", () => {
  hiMom.classList.add("red");
  hiMom.classList.remove("blue");
});

blueButton.addEventListener("click", () => {
  hiMom.classList.add("blue");
  hiMom.classList.remove("red");
});

whiteButton.addEventListener("click", () => {
  hiMom.style.color = "white";
});

blackButton.addEventListener("click", () => {
  hiMom.style.color = "black";
});

function logLastAttr(mutationRecordArray) {
  for (const record of mutationRecordArray) {
    if (record.type === "attributes") {
      log.textContent = `Updated attribute name: ${record.attributeName}`;
    }
  }
}

const observer = new MutationObserver(logLastAttr);
observer.observe(hiMom, { attributes: true });

結果

規範

規範
DOM
# ref-for-dom-mutationrecord-attributename②

瀏覽器相容性