JavaScript – Get Class Names of an HTML Element as String

To get the class names of a specific HTML Element as String, using JavaScript, get reference to this HTML element, and read the className property of this HTML Element.

className property returns the classes in class attribute separated by space, in a String.

In the following example, we will get the class names of the HTML Element, which is selected by id "myElement", as a String.

example.html

Try this html file online, and click on the Click Me button. Class names of this HTML Element will be printed to console, as shown in the following screenshot.

If the class attribute is empty or no class attribute is defined, then className property returns an empty string.

example.html

ADVERTISEMENT

Conclusion

In this JavaScript Tutorial, we learned how to get the class names of an HTML Element as String, using JavaScript.