Just as document.getElementById selects an element with a particular id value, getElementsByClassName gathers elements on a page that share a defined class value. As the plural name of the method suggests, getElementsByClassName collects an array of elements, never just one result… even if it matches only one element on the page.

If we have an element on the page:

<div class="eclipse"> … </div>

Then we can get it (and all other elements that use the class) using getElementsByClassName. As with getElementById, we usually place the result into a variable:

var totality = document.getElementsByClassName("eclipse");

As the first “slot” in the resulting array, the element could be shown in the console with:

totality[0]
> <div class="eclipse"> … </div>

Because the result will always be an array, you’ll need to loop through it in order to ensure that all the elements in the array are affected equally. Traditionally, this is achieved with a for loop, although there are many alternatives:

for (var i = 0; i < totality.length; i++) {
  // do something to totality[i];
}

Multiplicity

Elements can have multiple classes applied to them, so getElementsByClassName allows us to check for elements that use particular combinations of classes:

var totality = document.getElementsByClassName("eclipse partial");

The above JavaScript will only gather elements that have classes of both eclipse and partial applied to them.

Scope and Target

Unlike document.getElementById, getElementsByClassName can work from any location in a document, meaning that we can narrow our collection to the children of a particular element. For example, if we had a <nav> element that contained a series of links, and some of those links shared a particular class:

<nav id="mainnav">
    <a href="#">Home</a>
    <a href="#">Launch</a>
    <a href="#" class="multi">Options</a>
    <a href="#" class="multi">Hohmann Transfers</a>
    <a href="#" class="special">Belters</a>
</nav>

If we wanted to gain only the links that have the multi class, and wish to be assured that these links come solely from within the #mainnav element, we could do the following:

var nav = document.getElementById("mainnav");
var navlinks = nav.getElementsByClassName("multi");

Or alternatively, if we didn’t need to retain the reference to #mainnav:

var navlinks = document.getElementById("mainnav").getElementsByClassName("multi");

Conclusion

getElementsByClassName has excellent support in all modern browsers, including IE9+. Highly useful, it is surpassed in flexibility only by querySelectorAll, which we’ll be looking at next.