javascript get class name

JavaScript: How to Get Class Name

If you want to get the class name of an HTML element using JavaScript, then there are a couple of ways to do it.

Method 1: Using the className Property

The simplest and most straightforward method is to use the className property of the element object. This property returns a string that contains the class name(s) of the element separated by spaces.


const divElement = document.querySelector('div');
const className = divElement.className;
console.log(className);

In this example, we use the querySelector() method to select a div element and store it in the divElement variable. Then we use the className property to get its class name(s) and store it in the className variable. Finally, we log the class name(s) to the console.

Method 2: Using the classList Property

An alternative method is to use the classList property of the element object. This property returns a DOMTokenList object that contains the class name(s) of the element as individual items.


const divElement = document.querySelector('div');
const classList = divElement.classList;
console.log(classList);

In this example, we use the querySelector() method to select a div element and store it in the divElement variable. Then we use the classList property to get its class name(s) as a DOMTokenList object and store it in the classList variable. Finally, we log the DOMTokenList object to the console.

Note that the classList property also provides several methods to manipulate the class name(s) of the element, such as add(), remove(), toggle(), and contains().

Which Method Should You Use?

Both methods are equally valid, but the choice between them depends on your specific requirements.

  • The className property is simpler and more widely supported, but it returns a string that you may need to split or manipulate further.
  • The classList property is more advanced and provides additional methods for manipulating class name(s), but it returns a DOMTokenList object that you may need to iterate or convert to an array.

Choose the method that best suits your needs and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe