4

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
user1529413
  • 458
  • 8
  • 19

1 Answers1

15

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
elclanrs
  • 92,861
  • 21
  • 134
  • 171