MutationObserver can be used to observe mutations to the tree of nodes. It’s designed as a replacement for Mutation Events defined in the DOM3 Events specification.
API
var observer = new MutationObserver(callback);
observer.observe(target, options); // Observe the desired node
observer.disconnect(); // Stop observing
observer.takeRecords(); // Empty and return the record queue
## Example: Random Image Loader
javascript
var matrix = document.querySelector("#imgs");
var imgServ = [
"http://lorempizza.com/i/380/240",
"http://lorempixel.com/380/240/"
];
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var size = matrix.childElementCount;
matrix.children[size - 1].src =
imgServ[Math.floor(imgServ.length * Math.random())] +
"#" + Math.random().toString(36).substring(7);
});
});
observer.observe(matrix, { childList: true });
setInterval(function() {
matrix.appendChild(document.createElement('img'));
}, 1000);
Don’t miss the spec!
#javascript#dom#web-api
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.