MutationRecord: oldValue プロパティ
Baseline
広く利用可能
この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。2015年7月以降、すべてのブラウザーで利用可能です。
MutationRecord の読み取り専用プロパティ oldValue は、観測対象のノードの変化前の文字データまたは属性の値を保持します。
値
以下の条件を満たす場合、変化した属性の前の値を表す文字列です。
MutationObserver.observe()の引数attributeOldValueがtrueMutationObserver.observe()の引数attributesがtrueまたは省略された- 変更の
typeがattributes
以下の条件を満たす場合、変化した CharacterData ノードの前の値を表す文字列です。
MutationObserver.observe()の引数characterDataOldValueがtrueMutationObserver.observe()の引数characterDataがtrueまたは省略された- 変更の
typeがcharacterData
それ以外の場合、このプロパティは null です。
例
>前の色を表示する
以下の例では、h1 の色をランダムな新しい色に変えるボタンがあります。MutationObserver により対象のノード (h1) の属性の変更を観測します。変更が検出されたら、オブザーバーは関数 logOldValue() を呼び出します。
関数 logOldValue() は、MutationRecord オブジェクトが格納された配列 mutationRecords を受け取ります。そして、MutationRecord オブジェクトの oldValue プロパティを、前の色で表示します。
HTML
html
<h1 id="h1">Hi, Mom!</h1>
<button id="changeColorButton">色を変える</button>
<p id="log"></p>
JavaScript
js
const h1 = document.getElementById("h1");
const changeValueButton = document.getElementById("changeColorButton");
const log = document.getElementById("log");
changeColorButton.addEventListener("click", () => {
// 十六進の色の値として用いるランダムな 6 桁の十六進数
const newColor = Math.floor(Math.random() * 16777215).toString(16);
h1.style.color = `#${newColor}`;
});
function logOldValue(mutationRecordArray) {
for (const record of mutationRecordArray) {
log.textContent = `前の値: ${record.oldValue}`;
log.style.cssText = record.oldValue;
}
}
const observer = new MutationObserver(logOldValue);
observer.observe(h1, {
attributes: true,
attributeOldValue: true,
});
結果
仕様書
| 仕様書 |
|---|
| DOM> # ref-for-dom-mutationrecord-oldvalue②> |