Technical post alert!

This is SO clever that I have to quickly write it up.  It’s similar jQuery’s .live() but rather than binding an event handler when an element is created, it adds a class (or does anything else that you like) to a dynamically-created instance of an element.


I had a piece of AJAX that printed a message by dynamically creating a new DOM element.  I wanted to change this message when a certain condition was true. However, the AJAX that created the element was a WordPress plugin that I didn’t want to hack the core of.  If nothing else a plugin update could overwrite my change.

So I needed a way of spotting when the element got created and running some code.

The “load” event applies to all objects but you can’t bind to the event until the element exists. I don’t QUITE understand why but the following doesn’t work:

jQuery().live('load', function () { ... } )

The Solution

Credit must go to @nicksnell on Twitter, who responded to my cry for help and introduced me to the DOM Mutation Events, such as DOMNodeInserted and DOMSubtreeModified.

Combining jQuery’s live() method with the DOMNodeInserted event gave me a way to trigger an action on a new element that was dynamically created.  Here’s some code:

jQuery('#dynamically-created-object').live('DOMNodeInserted', function () {
if (some_condition) {
jQuery(this).html('New Content Here!');

And here’s a JSFiddle with a little example.

Perhaps there’s an easier way? Feel free to use the comments to discuss.

(By the way, I’ve tested this and, though the DOM spec is from 2000 it seems to work in modern browsers only. IE9 and latest versions of Firefox, Chrome, Safari and Opera are good. Typically, IE6, 7 and 8 are not).