How to get HTML elements by class using JavaScript

JavaScript getElementsByClassName() method explained

Posted on March 29, 2021

The document.getElementsByClassName() method is used to get HTML elements by its class name. Suppose you have the following HTML <body> tag:

  <p class="myParagraph">Hello there!</p>
  <p class="myParagraph">Greetings</p>

You can grab both <p> tags in the example above by using getElementsByClassName() method. The tags will be returned as an array:

let paragraphs = document.getElementsByClassName("myParagraph");
console.log(paragraphs[0].innerHTML); // Hello there!
console.log(paragraphs[1].innerHTML); // Greetings

The getElementsByClassName() method always returns an array even if you only have one element with that class name. You can also retrieve elements with more than one class names as follows:

  <p class="paragraph italic">Hello there!</p>
  <p class="paragraph bold">Greetings</p>
  <p class="paragraph bold">How are you?</p>
    let paragraphs = document.getElementsByClassName("paragraph bold");
    console.log(paragraphs.length); // 2
    console.log(paragraphs[0].innerHTML); // Greetings
    console.log(paragraphs[1].innerHTML); // How are you?

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 whichever method fits your requirement best. Just remember that getElementsByClassName() method always returns an array even when you only have one matching element.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more