Is there an event that occurs after an element is added to a webpage?
Ideally I want to do this:
var div = createSomeDiv();
$(div).on("???", function() {
console.log("Div was added")
});
document.body.appendChild(div); //<---event would fire now
Note that mutation events are deprecated, in modern browsers you'd do this with mutation observers:
var onAppend = function(elem, f) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(m) {
if (m.addedNodes.length) {
f(m.addedNodes)
}
})
})
observer.observe(elem, {childList: true})
}
onAppend(document.body, function(added) {
console.log(added) // [p]
})
var p = document.createElement('p')
p.textContent = 'Hello World'
document.body.appendChild(p) // will trigger onAppend callback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With