# How to select DOM elements by class name using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 6, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-select-dom-elements-by-class-name

> A quick guide to learn how to select DOM elements by CSS class name in JavaScript.

The `getElementsByClassName()` method provides a quick way to select all [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript) elements that contain a specific CSS class in JavaScript. It returns an [`HTMLCollection`](https://attacomsian.com/blog/javascript-htmlcollection) object which is an array-like object containing a collection of HTML elements.

The following example demonstrates how you can use the `getElementsByClassName()` method to select and iterate over **all** HTML elements that have the `active` class name:

```javascript
const elems = document.getElementsByClassName('active')

// iterate over all HTML elements
for (const el of elems) {
  console.log(el.innerText)
}
```

Since `HTMLCollection` is neither a [`NodeList`](https://attacomsian.com/blog/javascript-nodelist) nor an array, you can not use the [`forEach()`](https://attacomsian.com/blog/javascript-foreach) method to iterate over its elements. Therefore, we used the [`for...of`](https://attacomsian.com/blog/javascript-for-of-loop) statement.

The `getElementsByClassName()` method works in all modern and old browsers, including Internet Explorer 9 and higher. Since it can only be used to select elements by class name, its usage is limited.

If you want more *flexibility* to select DOM elements by any arbitrary CSS selectors, use the [`querySelectorAll()`](https://attacomsian.com/blog/javascript-select-dom-elements-by-css-selectors) method instead:

```javascript
const elems = document.querySelectorAll('active')
```

Read [this guide](https://attacomsian.com/blog/getting-dom-elements-javascript) to learn more about different ways of getting DOM elements in JavaScript.
