Sometimes, we want to get notified when an element is added to the page with JavaScript.
In this article, we’ll look at how to get notified when an element is added to the page with JavaScript.
How to get notified when an element is added to the page with JavaScript?
To get notified when an element is added to the page with JavaScript, we can use the MutationObserver
constructor.
For instance, we write
const observerConfig = {
attributes: true,
childList: true,
characterData: true,
};
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
console.log(mutation.type);
});
resolve(mutations);
});
observer.observe(targetNode, observerConfig);
to create a MutationObserver
with a callback that runs when the DOM changes.
And we call observer
with the targetNode
DOM node object and the observerConfig
object.
In observerConfig
we set attributes
, childList
, and characterData
to true
to watch for changes in node attributes, node add or remove, and character data changes.
Conclusion
To get notified when an element is added to the page with JavaScript, we can use the MutationObserver
constructor.