Skip to content

Instantly share code, notes, and snippets.

@undfine
Created April 30, 2024 18:02
Show Gist options
  • Select an option

  • Save undfine/748154b617c0a522121c3066e5c1c340 to your computer and use it in GitHub Desktop.

Select an option

Save undfine/748154b617c0a522121c3066e5c1c340 to your computer and use it in GitHub Desktop.
JS - Observer for Elements added to the DOM
function observeElementAddedToDOM(elementId, callback) {
// Select the target node
var targetNode = document;
// Options for the observer (which mutations to observe)
var config = { childList: true, subtree: true };
// Callback function to execute when mutations are observed
var observerCallback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(function(node) {
if (node.id === elementId) {
// Execute the callback function when the element is added
callback();
// Disconnect the observer
observer.disconnect();
}
});
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(observerCallback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
}
// Example usage:
observeElementAddedToDOM('ELEMENT-ID', function() {
console.log('Element added to the DOM');
// Your logic here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment