document.getElementsByClassName() method is used to get HTML elements by its class name. Suppose you have the following HTML
<body> <p class="myParagraph">Hello there!</p> <p class="myParagraph">Greetings</p> </body>
You can grab both
<p> tags in the example above by using
getElementsByClassName() method. The tags will be returned as an array-like object called
let paragraphs = document.getElementsByClassName("myParagraph"); console.log(paragraphs); // HTMLCollection(2) console.log(paragraphs.innerHTML); // Hello there! console.log(paragraphs.innerHTML); // Greetings
getElementsByClassName() method always returns an array-like
HTMLCollection even if you only have one element with that class name. You can also retrieve elements with more than one class names as follows:
<body> <p class="paragraph italic">Hello there!</p> <p class="paragraph bold">Greetings</p> <p class="paragraph bold">How are you?</p> <script> let paragraphs = document.getElementsByClassName("paragraph bold"); console.log(paragraphs.length); // 2 console.log(paragraphs.innerHTML); // Greetings console.log(paragraphs.innerHTML); // How are you? </script> </body>
Keep in mind that even though you can access
HTMLCollection object’s value like an array, the
Array prototype object.
Array methods like
filter() can’t be called from an
If you want to do something with all elements that match your selection, you need to use the
querySelectorAll() method explained
querySelectorAll() method returns a
NodeList object that implements the
And that will be all about the
document.getElementsByClassName() method. Although there’s nothing wrong with using the method, selecting an element by using its
id attribute is generally preferred over the
class attribute because the
id attribute is more precise and returns only a single element.
But of course, the choice is up to you as the developer to use which method fits your requirement best.