LAST UPDATED: AUGUST 4, 2021
How to get class name using JavaScript?
Answer: Using getElementsByClassName()
method
We can get the class name of any HTML element using the getElementsByClassNames()
method. This method returns the array of elements because we can specify the same class name for more than one HTML element.
This method returns all elements in the document having a class name specified within the method as an HTMLCollection object. The HTMLCollection object represents the collection of nodes. These nodes can be accessed by the index number starts at 0.
Example: Using getElementsByClassName()
method
In the given example, we have used the getElementsByClassName()
method to get all the elements with the specified class name myClass.
<!DOCTYPE html>
<html>
<head>
<title>Getting class name using getElementsByClassName()</title>
</head>
<body>
<div class="myClass">First div element with class name "myClass".</div>
<div class="myClass">Second div element with class name "myClass".</div>
<button onclick="myFunction()">Click Here</button>
<script>
function myFunction() {
var x = document.getElementsByClassName("myClass");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
Output
Before clicking on the button
After clicking on the button
Using getElementsByTagName()
method
We can also get class name using JavaScript getElementsByTagName()
method. This method returns the collection of elements with a specified tag name.
So, we are going to add background color to all the div elements having class name myClass using getElementsByTagName()
.
Example: Using getElementsByTagName()
method
In the given example, we have set the background color of all the div elements having class name myClass using getElementsByTagName()
method.
<!DOCTYPE html>
<html>
<head>
<title>Getting class name using getElementsByClassName()</title>
</head>
<body>
<div class="myClass">First div element with class name "myClass".</div>
<div class="myClass">Second div element with class name "myClass".</div>
<div class="xyz">Third div element with class name "xyz".</div>
<script>
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].className == 'myClass') {
divs[i].style.backgroundColor = 'pink';
}
}
</script>
</body>
</html>
Output
Conclusion
In this lesson, we have discussed how to get the class name with JavaScript. JavaScript offers built-in getElementsByClassName()
method with the help of which we can get the class name. We can also get the class name of the element using the getElementsByTagName()
method.