# How to select DOM elements by tag 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-tag-name

> A short guide to learn how to select HTML elements from the DOM by tag names in JavaScript.

In JavaScript, the `getElementsByTagName()` method can be used to select HTML elements from the [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript) by their tag names. This method returns an array-like [`HTMLCollection`](https://attacomsian.com/blog/javascript-htmlcollection) object that contains a collection of HTML elements.

The following example demonstrates how to use the `getElementsByTagName()` method to extract a list of HTML elements from the DOM and then iterate through them by using the [`for...of`](https://attacomsian.com/blog/javascript-for-of-loop) statement:

```javascript
const elems = document.getElementsByTagName('div')

// iterate using for...of loop
for (const div of elems) {
  console.log(div.innerText)
}
```

The `HTMLCollection` object is different than the [`NodeList`](https://attacomsian.com/blog/javascript-nodelist) and an array. Therefore, you can not use the ES6's [`forEach()`](https://attacomsian.com/blog/javascript-foreach) loop over `HTMLcollection` elements.

The `getElementsByTagName()` method *only* works in all modern browsers and is not supported by old browsers like Internet Explorer. Also, it is only limited to selecting elements by their tag name.

For better browser support and to select DOM elements by any arbitrary CSS selector, use the [`querySelectorAll()`](https://attacomsian.com/blog/javascript-select-dom-elements-by-css-selectors) method:


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

Check out [how to select DOM elements](https://attacomsian.com/blog/getting-dom-elements-javascript) tutorial to learn more about different ways of getting DOM elements in JavaScript.
