jQuery
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.
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.
We will first solve this by step-by-step process then we will solve the same problem by chaining methods.
To select the element we have to use the following code.
var h1 = $("#username");
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");
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");
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");
For this we write the following code.
$("#username");
Now we will add the text "happy" to the selected element by using the text()
method.
$("#username").text("happy");
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");
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 :-)
ADVERTISEMENT