views:

216

answers:

1

How do I detect the changes in DOM like innerHTML updated etc using JQuery's livequery.

I tried like below

Script -

var matched = function() {
     alert('detected');
};
var unmatched = function() {
    alert('removed')
};

$('div#container').livequery(matched, unmatched)

HTML -

<BODY onload="setTimeout(function(){
     document.getElementById('container').innerHTML = 'updated test'; },3000);">

  <div id="container">test</div>
 </BODY>

But this doesn't work.

Thanks, Sourabh

+2  A: 

What you are trying to do is not what the livequery-plugin is designed to do.

$('div#container').livequery(matched, unmatched);

This tells livequery to:

  • call the matched function when a div with id container is found or added to the DOM with one of the jQuery DOM-manipulation methods
  • call the unmatched function when a div with id container previously found was removed (or id changed) from the DOM with one of the jQuery DOM-manipulation methods

So with your sample it will only fire an alert saying detected on page load. As the innerHTML change doesn't neither add nor remove a div with id container livequery is supposed to do nothing and that is what it does.


Using * (instead of div#container) will only fire a couple of alerts on page load but again won't fire as long as you use non jQuery DOM-Manipulation methods.

document.getElementById('container').innerHTML = 'updated test';

Doesn't fire matched() as #1 you don't use jQuery to do the manipulation; #2 you don't add a new element which * would match.

document.getElementById('container').innerHTML = '<p>updated test</p>'

Doesn't fire matched() as you don't use jQuery to do the manipulation (although you add a element <p> which would be matched by the * selector but isn't registered by livequery as it only listens for jQuery DOM-manipulation methods (and only a selection of them too).

If instead you use

$("#container").html('<p>updated test</p>');

It will fire matched() after 3s. If you only do

$("#container").html('updated test');

matched() won't be fired as nothing was added that would be matched by the * selector only the innerHTML of an already matched element was changed

jitter