You can use the MutationObserver
API to observe changes to the DOM and trigger a function when a specific element is added to the DOM. Here’s an example of how to use MutationObserver
:
// Select the node that will be observed for mutations
const targetNode = document.getElementById('my-element');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
const addedNode = mutation.addedNodes[0];
if (addedNode.id === 'my-element') {
// Do something with myElement
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
In this example, we first select the node we want to observe for mutations (targetNode
). We then define the options for the observer (config
) and the callback function that will be executed when mutations are observed (callback
).
The callback
function checks for mutations of type childList
(i.e. the addition or removal of a child node) and if a node is added, it checks if the added node has the id my-element
. If it does, we can then do something with that element.
Finally, we create an instance of the MutationObserver
class and start observing the target node for mutations using the observe()
method.
Here’s a good video on MutationObserver by Web Dev Simplified -> (1) This Is Unbelievably Powerful – YouTube
