Course contentsShow
← Web Development
Lesson 677 of 2,98212. The Document Object ModelFree lesson

document.getElementsByTagName()

Select all elements of a specific tag type, useful for targeting semantic groups of elements.

Selecting Elements by Tag Name

You'll learn how to grab all elements of the same HTML tag type in one go using document.getElementsByTagName().

What It Does

document.getElementsByTagName() lets you select every element with a specific tag name—like all the <p> paragraphs, all the <div> containers, or all the <img> images on a page. Think of it like calling out "everyone wearing blue shirts" in a crowd—you get a collection of everyone matching that description.

How It Works

You pass the tag name as a string, and the method returns a live HTMLCollection of all matching elements:

// Get all paragraph elements
const allParagraphs = document.getElementsByTagName('p');

// Get all list items
const allListItems = document.getElementsByTagName('li');

// Get all images
const allImages = document.getElementsByTagName('img');

The tag name is case-insensitive in HTML documents, so 'P' and 'p' work the same way.

Working with the Results

Since you get an HTMLCollection (which is array-like), you can access elements by index or loop through them:

const headings = document.getElementsByTagName('h2');

// Access the first h2
console.log(headings[0]);

// Check how many h2 elements exist
console.log(headings.length);

// Loop through all h2 elements
for (let i = 0; i < headings.length; i++) {
  console.log(headings[i].textContent);
}

When to Use It

This method is perfect when you need to work with semantic groups—all links, all headings, all paragraphs. It's especially useful for bulk operations like "change the color of every link" or "count all images on the page."

Key Takeaway: document.getElementsByTagName() selects all elements matching a specific HTML tag, returning a live HTMLCollection you can iterate through or access by index.