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 using the jQuery JavaScript library.

Getting the class name of an HTML element is easy. There is a method available in jQuery that is attr() method that we can use to find any attribute value. We just need to pass the attribute name inside the method. This feature of the attr() method can be helpful to get the class name of our clicked element.

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

element.attr("class");

In HTML, classes are also a specific type of attribute. Browsers understand classes as special types of attributes and thus we can play with them in CSS as well as JS.

Now suppose we have the paragraph element with the 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. As we already know, the classname is theClass. So let’s see how we can find it programmatically.

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
   alert(className);
});

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

Also, read:

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;
   alert(theClass);
});

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 as we see in our first example.

Leave a Reply

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