This post will discuss how to get the class name of an element in JavaScript and jQuery.

1. Using jQuery

A simple and fairly efficient solution to getting the value of an element’s class attribute is to use jQuery’s .attr() method. This method is demonstrated below:

jQuery


HTML


CSS



Edit in JSFiddle

 
Alternatively, you can directly access the className property, which represents the contents of the element’s class attribute.

jQuery


HTML


CSS



Edit in JSFiddle

2. Using JavaScript

In plain JavaScript, you can get the value of the class attribute of the specified element with className property, as shown below:

JS


HTML


CSS



Edit in JSFiddle

 
Alternatively, you can use the querySelector() method like below.

JS


HTML


CSS



Edit in JSFiddle

That’s all about getting the class name of an element in JavaScript and jQuery.