简体   繁体   中英

How can I listen for an element being inserted into the DOM with jQuery without using custom triggers?

I want to listen for another piece of code that inserts some html into the page. I don't control that code, so I can't do .trigger('custom_event') and $(document).on('custom_event')

Additionally, the inserted div that I want to listen for is nested inside of the inserted html.

Here's what I have right now:

$(document).on('DOMNodeInsertedIntoDocument', "#inserted", function () {
    console.log("Inserted into document:", $(this));
});

$(document).ready(function () {
    var new_node = $('<div><div id="inserted">New Div</div></div>');
    $("body").append(new_node);
});

http://jsfiddle.net/AeHxQ/5/

Why doesn't the event get triggered?

You can use CSS animations with a little JavaScript, to detect when an element has been added to the DOM. The technique is explained here: http://davidwalsh.name/detect-node-insertion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM