How Can We Help?
< All Topics


Introduction to JavaScript getElementsByTagName() method

The getElementsByTagName() is a method of the document object or a specific DOM element.

The getElementsByTagName() method accepts a tag name and returns a live HTMLCollection of elements with the matching tag name in the order which they appear in the document.

The following illustrates the syntax of the getElementsByTagName():

let elements = document.getElementsByTagName(tagName); 

The return collection of the getElementsByTagName() is live, meaning that it is automatically updated when elements with the matching tag name are added and/or removed from the document.

Note that the HTMLCollection is an array-like object, like arguments object of a function.

JavaScript getElementsByTagName() example

The following example illustrates how to use the getElementsByTagName() method to get the number of H2 tags in the document.

When you click the Count H2 button, the page shows the number of H2 tags:

<!DOCTYPE html>
    <title>JavaScript getElementsByTagName() Demo</title>
    <h1>JavaScript getElementsByTagName() Demo</h1>
    <h2>First heading</h2>
    <p>This is the first paragraph.</p>
    <h2>Second heading</h2>
    <p>This is the second paragraph.</p>
    <h2>Third heading</h2>
    <p>This is the third paragraph.</p>

    <button id="btnCount">Count H2</button>

        let btn = document.getElementById('btnCount');
        btn.addEventListener('click', () => {
            let headings = document.getElementsByTagName('h2');
            alert(`The number of H2 tags: ${headings.length}`);


How it works:

  • First, select the button Count H2 by using the getElementById() method.
  • Second, hook the click event of the button to an anonymous function.
  • Third, in the anonymous function, use the document.getElementsByTagName() to get a list of H2 tags.
  • Finally, show the number of H2 tags using the alert() function.


  • The getElementsByTagName() is a method of the document or element object.
  • The getElementsByTagName() accepts a tag name and returns a list of elements with the matching tag name.
  • The getElementsByTagName() returns a live HTMLCollection of elements. The HTMLCollection is an array-like object.v

Table of Contents