Return Value of jQuery Setter Methods
In jQuery, understanding the return value of setter methods is fundamental to writing efficient and clean JavaScript code. Most jQuery setter methods return the jQuery object itself, representing the set of matched elements. This article explains the exact return value of these methods, why they are designed this way, how they enable method chaining, and how they differ from getter methods.
The jQuery Object as a Return Value
When you use a jQuery method to modify the DOM, alter attributes, or
apply styles, jQuery almost always returns the original jQuery selection
(the this object).
For example, consider the .css() method when used as a
setter:
let elements = $('p').css('color', 'blue');The variable elements holds the same jQuery collection
of <p> tags that was originally selected. It does not
return a boolean indicating success, nor does it return the modified
style value.
The Purpose: Enabling Method Chaining
The primary reason jQuery setter methods return the jQuery object is to facilitate method chaining. Chaining allows developers to run multiple commands in sequence on the same selection of elements without querying the DOM repeatedly or saving the selection to an intermediate variable.
Because each setter returns the target collection, you can link several methods directly together:
$('#message')
.text('Your profile has been updated.')
.addClass('alert-success')
.fadeIn(300);In this sequence, .text() updates the content and
returns $('#message'). Then, .addClass()
applies the class to that returned object and passes it along to
.fadeIn().
Common Setter Methods
Many jQuery methods function as both getters and setters depending on the arguments provided. When passed parameters that set values, the following methods all return the jQuery object:
- DOM Manipulation:
.html(content),.text(content),.append(content) - CSS and Classes:
.css(property, value),.addClass(className),.removeClass(className) - Attributes and Properties:
.attr(attributeName, value),.prop(propertyName, value) - Form Elements:
.val(value) - Dimensions:
.width(value),.height(value)
Setter Methods vs. Getter Methods
While setter methods return the jQuery collection to maintain
chaining, getter methods break the chain. When you call
the same methods without value arguments (such as .text(),
.val(), or .attr('id')), jQuery acts as a
getter.
Getters do not return the jQuery object; instead, they return the requested data (such as a string, number, or boolean) for the first element in the matched set:
$('input').val('John');(Setter) returns the jQuery object containing theinputelements.let name = $('input').val();(Getter) returns the string"John".