Javascript get class name

This article will explore different ways to get CSS class name of an element using javascript and jQuery.

Method 1: Using className
An element in javascript can be accessed using its id with getElementById() of document object.
This element has a className property which refers to the CSS class in HTML DOM.

For this example, the HTML is as below

<html>
  <head>
    <style>
      .red{ color:red }
    </style>
  <body>
    <div id="ele" class="red">Get Class with javascript</div>
  </body>
</html>

Below javascript code selects the div using its id and gets its CSS class using its className property as shown below.

<script>
  let class = document.getElementById('ele').className;
  // prints red
  console.log(class);
</script>

Method 2: Using classList property
We can also get CSS class of an element using its classList property. This property is a read only property which returns a list of CSS classes applied to an element.
classList returns an object. In order to get the class applied over an element, use value property of the returned value. Example,

<script> 
  let c=document.getElementById('ele').classList.value;
  // prints red
  console.log(c);
</script>

Method 3: Using jQuery prop()
If you are using jQuery, then use its prop() method. It takes the name of property of an element and returns its value.

Select the element with jQuery and invoke prop() method supplying it “class” as value, since CSS class is applied with “class” property.

Below code selects the div using its id and applies the required class.

<script> 
 let c = $('#ele').prop('class)'; 
 // prints red
 console.log(c);
</script>

Method 4: Using jQuery attr()
With jQuery, you can also get the CSS class of an element with its attr() method. It takes the name of attribute of an element and returns its value.

Select the element with jQuery and invoke attr() method supplying it “class” as value, since CSS class is applied with “class” property.

Below code selects the div using its id and applies the required class.

<script> 
  let c = $('#ele').prop('class)'; 
  // prints red 
  console.log(c); 
</script>

To sum, we can get CSS class of an element in javascript with className and classList property after selecting an element with document object.
Class name can also be retrieved using jQuery with its prop() and attr() methods with “class” as argument.
Hope the article was useful.