jQuery this Keyword

Ankit Raj Goyal Jul 29, 2022
  1. jQuery this Keyword as DOM Element
  2. Use jQuery this Keyword as DOM Element Inside a Callback
  3. Use jQuery this Keyword as DOM Element Inside the Callback of the each() Method
  4. Use jQuery this Keyword as DOM Element in the AJAX load() Method
  5. Use jQuery this Keyword as DOM Element in the Callback to the filter() Method
  6. Use jQuery this Keyword as General Object
  7. Use jQuery this Keyword as jQuery Object Inside a Plug-In
jQuery this Keyword

The jQuery this keyword thus lets developers use methods and properties of the current object without making fresh searches or look-ups. This tutorial shows several use cases of the this keyword in different contexts.

jQuery this Keyword as DOM Element

The most common use of the jQuery this keyword is when it refers to a DOM element. You can even have a thumb rule that if you are not specifically making jQuery plug-ins, you would most likely use this use case.

The jQuery this keyword might confuse you at first. jQuery (and other programming languages) provide the this keyword as a helpful tool, and in most cases, the value of the jQuery this keyword is easy to figure out - it points to the object, class or entity that intuitively it should refer to.

Use jQuery this Keyword as DOM Element Inside a Callback

The most likely entity the code inside your callback needs to refer to is the DOM element that the callback listens on. So, jQuery sets the this keyword in this case to the calling DOM element. (You can see our thumb rule works pretty well.)

Code - JavaScript + jQuery:

// this as a jQuery DOM button element inside a callback
$("#DOM_button").on("click",function(){
    $("p").html(`The value of 'this' keyword inside the DOM button element is ${$(this).attr('id')}`);
    //use case - you can deactivate the button easily without another DOM search call
    $(this).prop("disabled",true);
});

Code - HTML:

<body>
    <div id="triggers">
        <!-- Button DOM element -->
        <button id="DOM_button">I am a DOM button element</button>
    </div>
</body>

Our code logs the value of the this keyword inside the callback to the click event handler that listens on the DOM_button element. You might want to change some properties of the DOM element that the event handler listens to.

For example, we disable the DOM_button element. This is a common use case of the this keyword in this context.

Output:

&rsquo;this&rsquo; as the DOM Element Inside a Callback

Use jQuery this Keyword as DOM Element Inside the Callback of the each() Method

When you iterate over a jQuery collection with the each() method, you would want to access each DOM element inside the callback. jQuery sets the this keyword inside the each method callback to the current DOM element.

Code - JavaScript + jQuery:

//this as each DOM element inside a jQuery collection
$("#div_button").on("click",function(){
    $("p").html(" ");
    $("#div_container>div").each(function(idx){
        $("p").append(`The value of 'this' keyword inside child div ${idx + 1} is ${$(this).attr('id')} <br>`);
    });
});

Code - HTML:

<body>
<div id="div_container">
            <button id="div_button">
                "each" Method Demo
            </button>
            <div id="first_div">
                I am the First Div <br>
            </div>
            <div id="second_div">
                I am the Second Div <br>
            </div>
            <div id="third_div">
                I am the Third Div <br>
            </div>
    </div>
</body>

Output:

&rsquo;this&rsquo; keyword inside the callback to each() method

jQuery assigns the this keyword to the current div element in each iteration.

Use jQuery this Keyword as DOM Element in the AJAX load() Method

When you make an AJAX call with the load() method in jQuery, it points the this keyword inside the callback to the DOM element on which you run the load() method.

Again, the value of the jQuery this keyword is in line without the thumb rule - in most cases, the this keyword points to the object, class or entity you would need to access naturally.

Code - JavaScript + jQuery:

// //ajax request with the load method
$("#ajax_btn").on("click",function(){
            $("#ajax_this").load("http://127.0.0.1:5500/code_files/test.html",
            function(){
                $("p").html(`The value of 'this' keyword inside the 'load' method to send the                           AJAX request is ${$(this).attr('id')}`);
                //use case - you want to style it when a successful data fetch completes
                $(this).css("color","green");
            })
        });

We run the jQuery AJAX load method to fetch data from the test.html file on the same server. We output the value of the this keyword inside the callback to the load() method, which runs when the AJAX request completes.

Code - HTML:

    <div id="ajax_this">
        <button id="ajax_btn">
            AJAX Call Demo
        </button><br>
        <br>
        <div id="ajax_text">
            I demo the use of this as DOM element with an AJAX call
        </div>
    </div>

Output:

&rsquo;this&rsquo; as the DOM element on which we attach the AJAX &rsquo;load&rsquo; method

A common use case is when we want to color code the output in green on a successful AJAX call. For example, in our output demo above, we display the output in green.

In this example, we made an AJAX call to the test.html resource on the same server.

Code - test.html:

<title>Test HTML Page</title>
</head>
<body>
    <div id="main">
        <div id="top">
            <h3>
                We dish out a test page for our AJAX request on localhost.
            </h3>
        </div>
        <div id="mid">
            <h3>
                The request completes and returns the data that displays on the page.
            </h3>
        </div>

    </div>
</body>
</html>

Use jQuery this Keyword as DOM Element in the Callback to the filter() Method

When you use the filter() method on a jQuery collection to select a sub-set, you want to access the current DOM element in the collection on each iteration quickly. jQuery sets the this keyword inside the callback to the filter method to the current element.

The this keyword refers to the object we most intuitively expect it to.

Code - JavaScript + jQuery:

//this as the current DOM element inside the filter function in each iteration
$("#filter_this").on("click",function(){
    let $filterSet = $("div").filter(function(){
       return $(this).attr("id") == "selection_filter_this";
    });
    $("p").html(`The filtered set of div elements with the use of 'this' keyword are those with ID = : ${$filterSet.first().attr('id')}`);
});

Code - HTML:

<body>
<div id="selection_filter_this">
            <div id="filter_text">
                I demo the use of this as DOM element with a selector filter
            </div>
            <button id="filter_this">
                This keyword with the filter method
            </button>
        </div>
</body>

Output:

&rsquo;this&rsquo; keyword inside the callback to the &lsquo;filter&rsquo; method

We see that we filter div elements to select only those that match the ID, selection_filter_this with the this keyword in the callback. We then display the ID of the filtered element.

Use jQuery this Keyword as General Object

jQuery methods like the each() method can iterate over any array-like object. They do not only restrict to looping over DOM elements.

If we use a jQuery method like each() to loop over any array-like structure, we would naturally need access to the current entity in the iteration. So, jQuery sets the this keyword to the current object in such situations.

Code - JavaScript + jQuery:

// this as the current object in each iteration of the 'each' method
let objEachArr = ["First","Second","Third"];
$('#object_each_btn').on("click",function(){
    $("p").html("");
    $.each(objEachArr,function(curr){
        $("p").append(`The value of 'this' keyword in the current iteration of the 'each' method is  ${this} <br><br>`);
    });
});

Code - HTML:

<body>
<div id="object_each_div">
            <div id="object_each_text">
            I demo the use of 'this' as the current object in every iteration of the 'each' method.
            </div>
            <button id="object_each_btn">
                'This' in 'each' Method
            </button>
        </div>
    <div id="results">
        <p>
            We will display the results here.
        </p>
    </div>
</body>

We output the value of the this keyword in each iteration of the each method over the array objEachArr.

Output:

&rsquo;this&rsquo; keyword inside every iteration of the &rsquo;each&rsquo; method

We see that the this keyword refers to the current array element in each iteration of the each() method.

Use jQuery this Keyword as jQuery Object Inside a Plug-In

There is one special case for the jQuery this keyword. When we use the this keyword inside a plug-in, it refers to the jQuery object.

Code - JavaScript + jQuery:

/this as the jQuery Object inside a jQuery Plug-In
$.fn.plugInDemo = function(){
this.html(`The 'this' keyword inside my plug-in is the jQuery Object and we output the jQuery Version
 from this jQuery Object : ${this.jquery}`);
return this;
};

$("#plugin_btn").on("click",function(){
    $("p").plugInDemo();
});

Code - HTML:

<body>
<div id="plugin_div">
            <div id="plugin_text">
                I demo the use of 'this' inside a jQuery Plugin.
            </div>
            <button id="plugin_btn">
                'This' inside a Plug-In
            </button>
    </div>
    <div id="results">
        <p>
            We will display the results here.
        </p>
    </div>
</body>

We output the jQuery version by accessing the jQuery object via the this keyword inside our simple plug-in function plugInDemo.

Output:

&rsquo;this&rsquo; keyword inside a plug-in

The jQuery this keyword is a powerful tool to quickly access the current object, class or entity without making fresh DOM look-ups and is a great method to boost app performance.