Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Observe the contents of an 'a' tag - jquery

I have a blank <a> tag that content is loaded into via an external piece of javascript. I want to observe the <a> and when its content changes perform another task. The content will only ever change once.

Can this be done?

I am using also using jQuery.

Thanks in advance

like image 353
Lizard Avatar asked Mar 01 '11 13:03

Lizard


1 Answers

You can use a mixture out of jQuery && DOM Level 3 events (see browser support below).

If you want to check for any changes within the content, you could do this:

var $a = $('a');

$a.one('DOMNodeInserted', function(e) {
    console.log('content changed!: ', e);    

    console.log('new content: ', $(this).html());   
});

$a.one('DOMAttrModified', function(e) {
    console.log('attribute changed!: ');        

    console.log('attribute that was changed: ', e.attrName);
});

See this code in action: http://jsfiddle.net/wJbMj/1/

Reference: DOMNodeInserted, DOMAttrModified


While the above solution is actually pretty convinient to me, it'll only work in browser that support those events. To have a more generic solution, you can hook into jQuerys setter methods. The downside in this solution is, that you will only catch changes that were done through jQuery.

var _oldAttr = $.fn.attr;
$.fn.attr = function() {
    console.log('changed attr: ', arguments[0]);
    console.log('new value: ', arguments[1]);
    return _oldAttr.apply(this, arguments);
};

You could hook into .text() and .html() the exact same way. You would need to check if the this value within the overwritten methods represent the correct DOMnode.

like image 104
jAndy Avatar answered Oct 07 '22 20:10

jAndy