Method/ function chaining in jquery
In this topic, we will
learn function chaining in jquery with examples.
Function chaining in jquery
Function chaining is
one of the important features in jquery. Functions can be called one after
another and be chained together. Function chaining links two or more jQuery
actions, or methods, into a single statement to chain an action, you simply
append it to the previous action. Instead of selecting an element and calling a
method on it separately on each line, you can chain multiple methods calls one
after the other. Any function that returns
a jQuery object can be chained.
To check if a function
returns the jQuery object, see the top-right corner of its jQuery API documentation.
Can I chain all the functions in jquery?
The answer to the above question is No.
Because there are few methods that either can be chained or cannot be chained,
depending on how they are used.
One such method is text(). If you call text() with
no arguments, it will return the text of the element.
Function chaining – example:-
without function chaining:-
In the following example we have used the CSS(), text()
and add class() methods against the <h1> element on
three separate lines. Each line selected the <h1> element using
the same selector and the corresponding method was then invoked on the element.
with function chaining:-
Instead of selecting an element and
calling a method on it separately on each line, you can chain multiple methods
calls one after the other.
Share this article with your friends
Post A Comment:
0 comments: