Allen King
Allen King

Reputation: 2506

Attach a new method to jQuery object

I am trying to create a simple prototype that I can call on a DIV like this:

$('#mydiv').processHtml();

This is what I tried:

Object.prototype.processHtml = function() {
     var html = this.html();
     // call ajax.... 
}

But JavaScript throws as exception that html() is not a method. I tried HTMLDivElement instead of Object but it didn't help. Any pointers?

Upvotes: 0

Views: 35

Answers (1)

Andrew Li
Andrew Li

Reputation: 57934

You're modifying the wrong prototype -- you're trying to modify Object's prototype, but you have to modify jQuery's prototype because that's a jQuery object, not a JavaScript object. Hence the error, because a regular JavaScript object doesn't have the method html.

All jQuery methods are attached to the fn property of the jQuery object because the fn property is just an alias for the prototype:

jQuery.fn === jQuery.prototype

Thus, to add a method to the prototype of the jQuery object, you have to access the fn property (prototype) of the jQuery object, either:

jQuery.fn.processHtml = function() {
    ...
}

Or the $:

$.fn.processHtml = function() {
    ...
}

This will add the function to the prototype and share the method across all instances of a jQuery object:

$(selector).processHtml();

Upvotes: 1

Related Questions