To select HTML elements by their class names using JavaScript, you can use the getElementsByClassName
method. Here's an example on how to use it:
// Select elements with the class name "my-class"
const elements = document.getElementsByClassName("my-class");
// Loop through the selected elements
for (let i = 0; i < elements.length; i++) {
// Access each element
const element = elements[i];
// Do something with the element
console.log(element);
}
In the above example, document.getElementsByClassName("my-class")
selects all HTML elements with the class name "my-class" and returns a live HTMLCollection
of these elements. You can then loop through this collection to access and manipulate each element as needed.