The example below shows how onclick and $(this) work together. When using jQuery, we can use the click() method to make things even easier.

$("#div").click(function(){
    $(this).css("background-color", "green"); // Would change the background color of element #div to green
    $(this).hide(); // Results in the element #div being hidden
}); 

Another way this can be done is to use the .on() method:

$('#div').on("click", function(event) {
    $(this).hide(); // Results in the element #div being hidden (or display none).
});

Below is another example of using onclick and $(this).

Text 1

Text 2

$("#div1").click(function(){
    $("img", this).hide(); // Results in the img element inside of #div1 being hidden.
});

Categorized in:

jQuery,

Last Update: March 1, 2024