The method getElementsByClassName() returns an HTMLCollection object, which will have details about all elements with a specific class name. The method is case sensitive.
Let’s see an example
I have few <p> elements to show different birds and reptiles. The birds are defined using the class name .birds and the reptiles using class .reptiles.
<!DOCTYPE html> <html> <head> <title>JavaScript getElementsByClassName() Method</title> <style> .birds { font: 17px Calibri; color: #999; } .reptiles { font: 17px Calibri; color: red; } </style> </head> <body> <div> <p class='birds'>Rock Pigeon</p> <p class='birds'>Black Vulture</p> <p class='reptiles'>Snake</p> <p class='birds'>Mourning Dove</p> <p class='reptiles'>Lizard</p> <p class='reptiles'>Gecko</p> </div> <input type='button' id='bt' onclick='findEleByClass("birds")' value='Show'> <p id="msg"></p> </body> <script> let findEleByClass = (cls) => { let myclass = document.getElementsByClassName(cls); let msg = document.getElementById('msg'); for (i = 0; i <= myclass.length - 1; i++) { msg.innerHTML += myclass[i].innerHTML + '<br />'; } } </script> </html>
It is simple and doesn’t need a lengthy explanation. The method name itself says it all. Get elements by class name.
Inside the for loop, I am using the length property to find the number of the elements with a given class name. The name of the class is dynamically passed through the onclick event to a function.
Using getElementsByClassName() with Multiple Class Names
The getElementsByClassName() method can take multiple class names as parameter. So, you can find elements on your web page which has multiple class names. For example,
<!DOCTYPE html> <html> <head> <title>getElementsByClassName() Method with Multiple Class Names</title> <style> .birds { font: 17px Calibri; color: #999; } .cannot_fly { font: 17px Calibri; color: red; } </style> </head> <body> <div> <p class='birds'>Rock Pigeon</p> <p class='birds cannot_fly'>Ostriches</p> <p class='birds'>Mourning Dove</p> <p class='birds'>Black Vulture</p> <p class='birds cannot_fly'>Campbell teal</p> </div> <input type='button' id='bt' onclick='findEleByClass()' value='Show'> <p id="msg"></p> </body> <script> let findEleByClass = () => { let myclass = document.getElementsByClassName('birds cannot_fly'); // With multiple class names. let msg = document.getElementById('msg'); msg.innerHTML = ''; for (i = 0; i <= myclass.length - 1; i++) { msg.innerHTML += myclass[i].innerHTML + '<br />'; } } </script> </html>
Note: Multiple class names must be defined to the elements for the above method work properly. Else, you might not get the desired result.