• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / jQuery / onclick this jQuery

onclick this jQuery

November 24, 2021 Leave a Comment

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).

<div id="div1">
    <img src="#someurl">
    <p>Text 1</p>
    <p>Text 2</p>
</div>

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

Other Articles You'll Also Like:

  • 1.  Using jQuery to Remove Attribute from HTML Element
  • 2.  Using jQuery to Set the Width of a Div
  • 3.  Using jQuery to Change Div Text
  • 4.  Using jQuery to Change Inner HTML
  • 5.  jQuery Random Number Generator Between Two Numbers
  • 6.  Using jQuery to Replace HTML Inside Div
  • 7.  Sort List of Divs with Data Attribute with Radio Buttons Using Javascript
  • 8.  Using jQuery to Change the Id of a Div
  • 9.  Using jQuery to Change Text of HTML Element
  • 10.  Using jQuery to Set the Id of a Div

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy