To get you quickly started with using Mutation Observer
here's a small reusable function
/**
* Mutation Observer Helper function
* //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
* @param {string} sel The DOM selector to watch
* @param {object} opt MutationObserver options
* @param {function} cb Pass Mutation object to a callback function
*/
const Observe = (sel, opt, cb) => {
const Obs = new MutationObserver((m) => [...m].forEach(cb));
document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
To track only attribute "style" changes on some class="item" Elements, use like:
Observe(".item", {
attributesList: ["style"], // Only the "style" attribute
attributeOldValue: true, // Report also the oldValue
}, (m) => {
console.log(m); // Mutation object
});
To watch for all attributes changes, instead of the attributesList Array use :
attributes: true
If needed, here's an example:
/**
* Mutation Observer Helper function
* //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
* @param {string} sel The DOM selector to watch
* @param {object} opt MutationObserver options
* @param {function} cb Pass Mutation object to a callback function
*/
const Observe = (sel, opt, cb) => {
const Obs = new MutationObserver((m) => [...m].forEach(cb));
document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
// DEMO TIME:
Observe("#test", {
attributesList: ["style"],
attributeOldValue: true,
}, (m) => {
console.log(`
Old value: ${m.oldValue}
New value: ${m.target.getAttribute(m.attributeName)}
`);
});
const EL_test = document.querySelector("#test");
EL_test.addEventListener("input", () => EL_test.style.cssText = EL_test.value);
EL_test.style.cssText = EL_test.value;
* {margin:0;}
textarea {width: 60%;height: 50px;}
<textarea id="test">
background: #0bf;
color: #000;
</textarea>