Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event that occurs after appendChild

Tags:

javascript

dom

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
like image 229
user1529413 Avatar asked Sep 06 '25 03:09

user1529413


1 Answers

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
like image 185
elclanrs Avatar answered Sep 07 '25 21:09

elclanrs