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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Classes of HTML Element as String using JavaScript</h2>
<div id="myElement" class="abc xyz pqr">Hello World</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<script>
function execute(){
var element = document.getElementById('myElement');
var classes = element.className;
console.log(classes);
}
</script>
</body>
</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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Classes of HTML Element as String using JavaScript</h2>
<div id="myElement">Hello World</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<script>
function execute(){
var element = document.getElementById('myElement');
var classes = element.className;
console.log(classes);
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to get the class names of an HTML Element as String, using JavaScript.