Detect element content changes with jQuery

Elzo Valugi picture Elzo Valugi · Jul 7, 2009 · Viewed 229.4k times · Source

change() function works and detects changes on form elements, but is there a way of detecting when a DOM element's content was changed?

This does not work, unless #content is a form element

$("#content").change( function(){
    // do something
});

I want this to trigger when doing something like:

$("#content").html('something');

Also html() or append() function don't have a callback.

Any suggestions?

Answer

Kyle picture Kyle · Sep 1, 2010

I know this post is a year old, but I'd like to provide a different solution approach to those who have a similar issue:

  1. The jQuery change event is used only on user input fields because if anything else is manipulated (e.g., a div), that manipulation is coming from code. So, find where the manipulation occurs, and then add whatever you need to there.

  2. But if that's not possible for any reason (you're using a complicated plugin or can't find any "callback" possibilities) then the jQuery approach I'd suggest is:

    a. For simple DOM manipulation, use jQuery chaining and traversing, $("#content").html('something').end().find(whatever)....

    b. If you'd like to do something else, employ jQuery's bind with custom event and triggerHandler

    $("#content").html('something').triggerHandler('customAction');
    
    $('#content').unbind().bind('customAction', function(event, data) {
       //Custom-action
    });
    

Here's a link to jQuery trigger handler: http://api.jquery.com/triggerHandler/