
$(this) means “the element that triggered the current event or action, wrapped in jQuery so you can use jQuery methods on it.”
The two parts:
So, whatever be the event/method – like click, hover, each, blur. You can refer to the DOM element with $(this).
I have a list of li items, and I want the one I click to change color. To do this, I’ll use the jQuery $(this) selector, which gives me the clicked li element.
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 when it is clicked, I want to add some text to it. I will use $(this) to append the text to the clicked button.
<button>Click </button>
$("button").click(function () {
$(this).append("the button")
});
I have a textbox, and when it receives focus, I want to change its border. I will use the jQuery $(this) selector to target the textbox on its focus event.
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 the mouse hovers over it, the text is underlined, and when the mouse moves away, the underline is removed.
<span>Hover the mouse over me</span>
$("span").hover(function () {
$(this).css("text-decoration", "underline");
}, function () {
$(this).css("text-decoration", "none");
});
Download links: