jQuery – Chaining

In jQuery, chaining refers to the practice of applying multiple methods to a single jQuery object in a sequence. Chaining allows you to perform several operations on the same set of elements without repeatedly selecting them.

To understand chaining, let’s consider an example:

				
					<div id="myDiv">Hello, World!</div>

				
			
				
					// Select the div element and modify its CSS properties
$('#myDiv')
  .css('color', 'red')
  .addClass('highlight')
  .fadeOut(2000)
  .fadeIn(2000);

				
			

In this example, the $('#myDiv') selector selects the <div> element with the ID “myDiv”. After that, multiple methods are chained together:

  1. The .css('color', 'red') method sets the text color of the selected element to red.
  2. The .addClass('highlight') method adds the CSS class “highlight” to the element.
  3. The .fadeOut(2000) method gradually fades out the element over a duration of 2000 milliseconds (2 seconds).
  4. Finally, the .fadeIn(2000) method fades the element back in over a duration of 2000 milliseconds.

By chaining these methods together, you can perform multiple operations on the same element without reselecting it with $('#myDiv') each time.

Chaining is possible because most jQuery methods return the same jQuery object they were called on. This allows you to continue chaining additional methods as needed.

It’s important to note that not all jQuery methods support chaining. Some methods return values that aren’t jQuery objects, so you won’t be able to continue chaining after those methods. Always refer to the jQuery documentation for specific method chaining capabilities.

Join To Get Our Newsletter
Spread the love