Learn and Understand jQuery this “$(this)” Selector with Examples and Codes

Learn and Understand jQuery this “$(this)” Selector with Examples and Codes

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.

jQuery this refers exactly to the DOM element in Question.

So whatever be the event/method – like click, hover, each, blur. You can refer to the DOM element with $(this).

jQuery this – Click Example

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");
 });

jQuery this – .each() example

Now I will use the jQuery this selector with .each() method. I will use change the color of elements having class 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");
});
Note – I used jQuery CSS to change the color of element.

jQuery this – .append() example

I have a button and on its 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")
});
Text is appended to the button using jQuery Append Method.

jQuery this – .focus() example

Here I have a textbox on its 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");
});
You should also note that I am using .blur() event to remove the border from the textbox.

jQuery this – .hover() example

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");
});

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.