JavaScript’s Document.getElementsByClassName() method returns a live array-like object containing all the elements that have all the specified class names.

Syntax

Document.getElementsByClassName(parameter);

Parameter

A string containing one or more class names, separated by whitespace.

Return value

A live HTMLCollection containing all the elements that have all the specified class names. “Live” means that the collection is automatically updated when the underlying document is changed.

Examples

Here are some examples of using the JavaScript getElementsByClassName() method.

Suppose we have the following HTML elements:

<ul>
 <li class="menu-item">Home</li>
 <li class="menu-item">Blog</li>
 <li class="menu-item">Contact Me</li>
</ul>

How can we select the li elements?

We can use the getElementsByClassName() method:

let menuItems = document.getElementsByClassName('menu-item');

Now we have the elements selected and stored in the menuItems variable.

This is how we could iterate over the elements if we wanted to:

for (let menuItem of menuItems) {
 console.log(menuItem.textContent);
}

What if we were interested in only the first element?

Well, we could access the element by referring to its index number:

let firstElement = document.getElementsByClassName('menu-item')[0];
console.log(firstElement.textContent);
// Home

JavaScript arrays are zero-indexed, meaning that the first element of an array is at index 0, the second is at index 1, and so on

Browser compatibility

Chrome
Edge
Firefox
Internet Explorer
Opera
Safari
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
getElementsByClassName() 1 12 3 9 9.5 3.1 18 4 10.1 2 1.0 4.4

See also