jQuery - Chaining Methods

jQuery

Share


In this tutorial we will learn about chaining methods in jQuery.

In jQuery any method that returns a jQuery object can be chained.

In this tutorial we will look at how to add text, change text color and background color using chaining methods in jQuery. So, lets get started.

Adding text and style by chaining methods

Let's say we have an element h1 having id username. And lets say we want to add some text and change both the text color and the background color of the element.

In order to accomplish this task we have to do the following things.

  1. Select the element
  2. Add text
  3. Set text color
  4. Set background color

We will first solve this by step-by-step process then we will solve the same problem by chaining methods.

Step by step

Step 1: Select the element

To select the element we have to use the following code.

var h1 = $("#username");

Step 2: Add text

Lets say we want to add the username to the element. In order to achieve this we can use the text() method and pass the text value that we want to add.

h1.text("happy");

Step 3: Set text color

To set the text color we have to use the css() method. Lets say we want to change the text color to #111 so, we will write the following code.

h1.css("color", "#111");

Step 4: Set background color

To set the background color we have to again use the css() method. Lets say we want to set the background color to #eee so, we will write the following code.

h1.css("background-color", "#eee");

So, we have written the following 4 steps in order to set the text "happy" and change the text color to "#111" and background color to "#eee".

var h1 = $("#username");
h1.text("happy");
h1.css("color", "#111");
h1.css("background-color", "#eee");

Chaining methods

Step 1: Select the element

For this we write the following code.

$("#username");

Step 2: Set text

Now we will add the text "happy" to the selected element by using the text() method.

$("#username").text("happy");

Step 3: Set text color

For this we will use the css() method and the color property and we will set the value to #111.

$("#username").text("happy").css("color", "#111");

Step 4: Set background color

To set the background color we will again use the css() method and the background-color property and we will set the value to #eee.

$("#username").text("happy").css("color", "#111").css("background-color", "#eee");

But wait...

We can achieve the same result by combining Step 3 and Step 4.

So, the final code will look like the following.

$("#username").text("happy").css({"color": "#111", "background-color": "#eee"});

And we can also separate the methods to make it more readable.

$("#username")
  .text("happy")
  .css({
    "color": "#111",
    "background-color": "#eee"
  });

This is chaining of methods in jQuery. I will encourage you to try this yourself.

Have fun coding :-)

Share

Recently Added