How to get the class name of a clicked element in jQuery?

Today in this post we are going to see how we can get the name of the class of an element when someone clicks on the element. In short, we are going to get the class name of an element on click.

Getting the class name of an HTML element is easy. There is a method available in jQuery that is .attr(), which can be used to find any attribute value. We just need to pass the attribute name inside the method.

Here we want to get the class name. So we just have to pass the attribute name within the attr() jQuery method just like you can see below:


Now suppose we have the paragraph element with class name “theClass” just like below:

<p class="theClass">Click on me to see my class name</p>

Now as we want to get the class name of our paragraph element so we are going to use the jQuery click method.

Below is our jQuery code that will alert the class name of our clicked paragraph element:

$("p").click(function() {
   var className = $(this).attr("class");
   // alert the class name

Now we can test it on our browser and we will be able to see the class name appear in the JavaScript alert box.

Select element by its attribute in jQuery

Detect change in HTML select tag and get changed value in jQuery

An alternative method of getting the class name

Without the help of jQuery object, you can get the class name too. below is the code:

$("p").click(function() {
   var theClass = this.className;

In this case, we have used the JavaScript className object to get the class of our element. It will also alert the class name in the alert box like we see in our first example.

Leave a Reply

Your email address will not be published.