The jQuery this selector is widely used and many times people get confuse to understand it fully. Therefore I decided to write this tutorial which explains the usage of $(this) selector with some easiest examples.
So whatever be the event/method – like click, hover, each, blur. You can refer to the DOM element with $(this).
I have some li tags. I can change the color of the li which is clicked. Here I will use the jQuery this selector to get my clicked li tag.
Study the below code:
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
<li>forth</li>
</ul>
$("li").click(function () {
$(this).css("color", "orange");
});
Now I will use the jQuery this selector with .each() method. I will use change the color of elements having class called myclass.
Study the below code:
<ul>
<li class="myclass">has "myclass"</li>
<li>some text</li>
<li class="myclass">has "myclass"</li>
<li>some text</li>
</ul>
$("li.myclass").each(function () {
$(this).css("color", "purple");
});
I have a button and on it’s click event I will append a text to it. I will use $(this) to append the text.
<button>Click </button>
$("button").click(function () {
$(this).append("the button")
});
Here I have a textbox and on it’s focus event I will change its border using jQuery this selector.
The below code does this work:
<input type="text" placeholder="Some text" />
$("input").focus(function () {
$(this).css("border", "4px dashed yellow");
});
$(" input").blur(function () {
$(this).css("border", "none");
});
Now I will explain how to use $(this) with jQuery hover event.
I have a span element. When mouse hovers over it the text-decoration is underline and when mouse moves away from it then text-decoration is changed to none.
<span>Hover the mouse over me</span>
$("span").hover(function () {
$(this).css("text-decoration", "underline");
}, function () {
$(this).css("text-decoration", "none");
});
Download links: