To get multiple HTML elements using JavaScript, we can use the getElementsByClassName() method if all the elements share the same classname.
document.getElementsByClassName("classes")
The getElementsByClassName() method will return a collection of HTML elements. In this case, it will be HTML elements with the class name of “classes”.
Let’s say I have the following HTML:
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
If we want to make all the paragraphs with class “p” bold, we can do this with the getElementsByClassName() method and a for loop. The getElementsByClassName method will get all the elements with the class name we want. We then have to loop through each one to set the individual style for that element.
var allClasses = document.getElementsByClassName("p");
for (var i = 0; i < allClasses.length; i++) {
allClasses[i].style.fontWeight = "bold";
}
The resulting HTML would be as follows:
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
Using the getElementsByClassName Method With a Click
We can change multiple elements with the same class in HTML using JavaScript very easily by utilizing the getElementsByClassName method with an onclick event.
Let's say we have the following HTML code and we want to give the user the ability to change the styles of certain classes. The elements below will alternate with different classes, "odd", and "even". We will change the background color of the odd classes to give the divs a table-like style.
Here is the HTML:
This is an odd paragraph.
This is an even paragraph.
This is an odd paragraph.
This is an even paragraph.
This is an odd paragraph.
Add styles
We can utilize both the onclick event and the getElementsByClassName() to change the background of each div with classname "odd".
Below is the Javascript code which will allow the user to be able to do this:
function clickFunction() {
var allClasses = document.getElementsByClassName("odd");
for (var i = 0; i < allClasses.length; i++) {
allClasses[i].style.backgroundColor = "#ffffff";
}
}
The final code and output for this example of using getElementsByClassName with JavaScript is below:
Code Output:
This is an odd paragraph.
This is an even paragraph.
This is an odd paragraph.
This is an even paragraph.
This is an odd paragraph.
Full Code:
This is an odd paragraph.
This is an even paragraph.
This is an odd paragraph.
This is an even paragraph.
This is an odd paragraph.
Add styles
<script>
function clickFunction() {
var allClasses = document.getElementsByClassName("odd");
for (var i = 0; i < allClasses.length; i++) {
allClasses[i].style.backgroundColor = "#ffffff";
}
}
</script>
Hopefully this article has been useful for you to understand how to use the getElementsByClassName method with JavaScript.