I\'m working on an Extension in Chrome, and I\'m wondering: what\'s the best way to find out when an element comes into existence? Using plain javascript, with an interval t
I think that still there isnt any answer here with easy and readable working example. Use MutationObserver interface
to detect DOM changes, like this:
var observer = new MutationObserver(function(mutations) {
if ($("p").length) {
console.log("Exist, lets do something");
observer.disconnect();
//We can disconnect observer once the element exist if we dont want observe more changes in the DOM
}
});
// Start observing
observer.observe(document.body, { //document.body is node target to observe
childList: true, //This is a must have for the observer with subtree
subtree: true //Set to true if changes must also be observed in descendants.
});
$(document).ready(function() {
$("button").on("click", function() {
$("p").remove();
setTimeout(function() {
$("#newContent").append("New element
");
}, 2000);
});
});
Note: Spanish Mozilla docs about
MutationObserver
are more detailed if you want more information.