javascript mutationobserver class - Event when element added to page

3 Answers

The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (

So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)

change jquery dom

This was previously discussed here: How to do an action when an element is added to a page using Jquery?

The responder suggested triggering a custom event whenever a div was added to the page. However, I'm writing a Chrome extension and don't have access to the page source. What are my options here? I guess in theory I could just use setTimeout to continually search for the element's presence and add my action if the element is there.

You can use livequery plugin for jQuery. You can provide a selector expression such as:

$("input[type=button].removeItemButton").livequery(function () {
    $("#statusBar").text('You may now remove items.');

Every time a button of a removeItemButton class is added a message appears in a status bar.

In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.

Revisited answer

The answer above was only meant to detect that an item has been added to the DOM through the plugin.

However, most likely, a jQuery.on() approach would be more appropriate, for example:

$("#myParentContainer").on('click', '.removeItemButton', function(){
          alert($(this).text() + ' has been removed');

If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on.

There's a promising javascript library called Arrive that looks like a great way to start taking advantage of the mutation observers once the browser support becomes commonplace.