大网数据广告活动
Web 标准与前端开发

MutationRecord: type property

· 52CE 我爱测

The MutationRecord read-only property **`type`** is the type of the MutationRecord observed by a MutationObserver.

DOM

The MutationRecord read-only property type is the type of the MutationRecord observed by a MutationObserver.

Value

The property is set to the type of the mutation as a string. The value can be one of the following:

  • attributes if the mutation was an attribute mutation.

  • characterData if it was a mutation to a CharacterData node.

  • childList if the mutation was a mutation to the tree of nodes.

Examples

Log the type of a mutation

The following example gives you two buttons to manipulate the DOM. The first button adds a new node to the example, and the second button changes the color attribute of all the added nodes. A MutationObserver is created to observe it all, and the observer is set to log the type of the mutation record to #log.

You'll notice the when you add a node, the type is childList, and when you change the color attribute, the type is attributes.

HTML

<button id="add-nodes">Add a node</button>
<button id="set-attribute">Change the color</button>

<button id="reset">Reset</button>

<pre id="log">Mutation type:</pre>
<div id="target"><p>Node #0</p></div>
#log {
  border: 1px dotted black;
  padding: 0.5rem;
}

.blue {
  color: blue;
}

.red {
  color: red;
}

JavaScript

const addNodes = document.querySelector("#add-nodes");
const setAttribute = document.querySelector("#set-attribute");
const reset = document.querySelector("#reset");
const log = document.querySelector("#log");
const target = document.querySelector("#target");
let nodeNumber = 1;

addNodes.addEventListener("click", () => {
  const newPara = document.createElement("p");
  newPara.textContent = `Node #${nodeNumber}`;
  nodeNumber++;
  target.appendChild(newPara);
});

setAttribute.addEventListener("click", () => {
  if (target.getAttribute("class") === "red") {
    target.setAttribute("class", "blue");
  } else {
    target.setAttribute("class", "red");
  }
});

reset.addEventListener("click", () => self.location.reload());

function logMutationType(records) {
  for (const record of records) {
    log.textContent = `Mutation type: ${record.type}`;
  }
}

const observer = new MutationObserver(logMutationType);
observer.observe(target, { childList: true, attributes: true, subtree: true });

Result

Log the type of a mutation

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。