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②

浏览器兼容性