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

MutationRecord: oldValue property

· 52CE 我爱测

The MutationRecord read-only property **`oldValue`** contains the character data or attribute value of an observed node before it was changed.

DOM

The MutationRecord read-only property oldValue contains the character data or attribute value of an observed node before it was changed.

Value

A string representing the old value of an attribute which has been changed, if:

  • the attributeOldValue parameter to MutationObserver.observe() is true
  • the attributes parameter to MutationObserver.observe() is true or omitted
  • the mutation MutationRecord.type is attributes.

A string representing the old value of a CharacterData node that has been changed, if:

  • the characterDataOldValue parameter to MutationObserver.observe() is true
  • the characterData parameter to MutationObserver.observe() is true or omitted
  • the mutation MutationRecord.type is characterData.

Otherwise this property is null.

Examples

Show old color value

In the following example, there is a button that changes the color of an h1 to a random new color. A MutationObserver is used to observe the target node (h1) for changes to the attribute; when a change is detected, the observer calls a function, logOldValue().

The logOldValue() function is passed the mutationRecords array, which contains the MutationRecord objects. The oldValue property of the MutationRecord object is then displayed, in the color of the old value.

HTML

<h1 id="h1">Hi, Mom!</h1>
<button id="changeColorButton">Change color</button>
<p id="log"></p>

JavaScript

const h1 = document.getElementById("h1");
const changeValueButton = document.getElementById("changeColorButton");
const log = document.getElementById("log");

changeColorButton.addEventListener("click", () => {
  // Random 6 character hexadecimal number to use as the hex color value
  const newColor = Math.floor(Math.random() * 16777215).toString(16);
  h1.style.color = `#${newColor}`;
});

function logOldValue(mutationRecordArray) {
  for (const record of mutationRecordArray) {
    log.textContent = `Old value: ${record.oldValue}`;
    log.style.cssText = record.oldValue;
  }
}

const observer = new MutationObserver(logOldValue);
observer.observe(h1, {
  attributes: true,
  attributeOldValue: true,
});

Result

Show old color value

Specifications

Browser compatibility

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

资料来源与适用范围

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

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

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