What Is the jQuery $.fn.extend() Method?
The jQuery $.fn.extend() method is a built-in function
used primarily to extend the jQuery prototype, allowing developers to
create custom plugins and chainable methods for DOM element selections.
This article explains the exact purpose of $.fn.extend(),
how it works under the hood, how it differs from
$.extend(), and how to use it to write reusable jQuery
functions.
The Purpose of
$.fn.extend()
In jQuery, $.fn is an alias for
jQuery.prototype. Any method added to $.fn
becomes available to all jQuery selection objects (elements wrapped by
$()). The primary purpose of $.fn.extend() is
to merge an object containing custom methods directly into
jQuery.prototype, enabling developers to add new, custom
functionality to matched DOM nodes.
Without extending the prototype, you would need to write standalone
utility functions. Using $.fn.extend() allows your code to
integrate seamlessly into jQuery's native, chainable syntax.
Syntax and Basic Usage
The method accepts an object where the keys are the method names and the values are the corresponding functions:
$.fn.extend({
highlight: function() {
return this.css("background-color", "yellow");
}
});Once defined, the highlight() method can be called on
any jQuery object:
$("p").highlight();Key Characteristics
- The
thisKeyword: Inside a method defined with$.fn.extend(),thisrefers to the current jQuery collection, not a raw DOM element. There is no need to re-wrapthiswith$(this)unless you are iterating through elements. - Method Chaining: To maintain jQuery’s signature
method chaining, the custom method should typically return
this. For example,return this.each(...)allows callers to continue chaining additional jQuery methods like.show()or.addClass().
$.fn.extend({
makeRed: function() {
return this.each(function() {
$(this).css("color", "red");
});
}
});
// Chaining works as expected:
$("h2").makeRed().fadeOut();Difference Between
$.extend() and $.fn.extend()
A common point of confusion is the distinction between
$.extend() and $.fn.extend():
$.extend()adds utility methods directly to the globaljQueryobject (static methods) or merges two JavaScript objects together. Methods added here are called without selecting elements, such as$.myUtility().$.fn.extend()adds methods to the jQuery prototype. Methods added here operate directly on selected DOM elements, such as$("selector").myMethod().