How to detect new element creation in jQuery?

serg picture serg · Aug 2, 2010 · Viewed 44.6k times · Source

Lets say I have the following code that returns number of anchor elements on a page:

function getLinkCount() {
    alert("Links:" + $("a").length);
}

If I call in on document ready it would work as expected. But what if now a new link gets inserted into a page dynamically through javascript, how can I get notified to run link counter function again? (I have no control over a script that could create a new link).

Basically I am looking for something similar to live() only that would be watching element creation event, something like:

$("a").live("create", getLinkCount);

that would trigger when a new element is created.

Answer

mattsh picture mattsh · Aug 2, 2010

You could use the DOMSubtreeModified event. For example:

$(document).bind('DOMSubtreeModified',function(){
  console.log("now there are " + $('a').length + " links on this page.");
})