www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons jQuery Method Chaining Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Most of the jQuery methods return a jQuery object. So, why is this important?

This is very important as we can achieve something called method chaining by using the jQuery object returned by its methods.

Recall from the previous lesson, where we use the following line of code to change the text of our <div> tag:

$ ( "#hello" ). text ( "Hello world!" );

What if we now need to change the css associated with the above tag. In that scenario we need to write yet another line of code as follows:

$ ( "#hello" ). css ( "color", "orange" );

As has already been said that most of the jQuery methods return jQuery object. W can use the returned object to do method chaining, where we can call or invoke multiple methods on the same set of elements. This also makes our code neat and clean, besides making it efficiet. The following example would make this point clearer:

<div id = "hello" ></div>
<script type = "text/javascript" >
$ ( "#hello" ). text ( "Hello world!" ). css ( "color" , "orange" );

Lets try to comprehend the above code.
  • We initiate a new jQuery object and select the <div id="hello"> element with the $ symbol.
  • Remember that the $ symbol is a shortcut for the jQuery class.
  • We get a jQuery object that allows us to manipulate the selected element.
  • We call the text() method on the jQuery object, that sets the text of the selected element.
  • The text() method returns the jQuery object again, that allows us to call another method on the same object.
  • Using the . operator we call another method css() on the same object and on the same line of code.

More method calls can be added on the same line.

Before using the method chaining, we have to have a knowledge of which methods return jQuery object and which methods do not. Even some methods return a jQuery object depending upon the parameters they receive. For example the text() method returns a jQuery object only if we pass it a single argument. If we do not pass it a parameter, it returns the current text of the selected element(s).
Next >>> Lesson No. 6: jQuery Selectors

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.