tags:

views:

108

answers:

2

Hi to all,

how can I overload or extend (or intercept) jQuery's .html() method so that it works its default way unless the object has a certain class?

Thanks

+5  A: 

You just overwrite the function while maintaining a reference to the original.

var jq_html_function = $.fn.html;

$.fn.html = function() {
    $(this).each(function() {
        if($(this).hasClass('someclass')) {
            // Do something
            return;
        }
        jq_html_function.apply(this, arguments);
    });
};
BC
Well, that's not really so good of an idea. The call to `hasClass()` will return true if *any* of the elements in the jQuery list have the class.
Pointy
@Pointy good point i can revise.
BC
OK I'll delete mine then
Pointy
+1  A: 

Isn't that bit of a hacky solution? I think we should let the framework be as it is. What if you wanted to use new version of jQuery, or if you hired new developer who needed to use unmodified .html() ?

Why not:

$('.blah').setHtml('<div>something</div>');

Where:

(function($)
{
    $.fn.setHtml = function(html)
    {
        if (html.parse_for_class == true)
        {
            //do something with it
        }
        else 
        {
            $(this).html(html);
        }
        return;
    }
}
rochal
I agree that changing the function is terribly scary, but it has the advantage that code all over the place - including code inside jQuery itself, for example, like when you call `load()` - will also use the overridden version.
Pointy