In JavaScript, the getElementsByClassName() method is used to retrieve a collection of all elements in the document that have a specified class name. Here’s how it works:
// Get all elements with the class name "example"
var elements = document.getElementsByClassName("example");
// Loop through the collection of elements
for (var i = 0; i < elements.length; i++) {
// Do something with each element, for example, log its inner text
console.log(elements[i].innerText);
}
This script will retrieve all elements with the class name “example” and log their inner text to the console. Keep in mind that getElementsByClassName()
returns a live collection, so if the DOM is modified after the collection is created, the collection will update to reflect those changes.