I want a function of my choosing to run when a DOM element is added to the page. This is in the context of a browser extension, so the webpage runs independently of me and I
A pure javascript solution (without jQuery
):
const SEARCH_DELAY = 100; // in ms
// it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
function waitForElementToBeAdded(cssSelector) {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (element = document.querySelector(cssSelector)) {
clearInterval(interval);
resolve(element);
}
}, SEARCH_DELAY);
});
}
console.log(await waitForElementToBeAdded('#main'));
Check out this plugin that does exacly that - jquery.initialize
It works exacly like .each function, the difference is it takes selector you've entered and watch for new items added in future matching this selector and initialize them
Initialize looks like this
$(".some-element").initialize( function(){
$(this).css("color", "blue");
});
But now if new element matching .some-element
selector will appear on page, it will be instanty initialized.
The way new item is added is not important, you dont need to care about any callbacks etc.
So if you'd add new element like:
$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
it will be instantly initialized.
Plugin is based on MutationObserver