JavaScript

getElementsByTagName - JavaScript DOM Reference

Guide to getElementsByTagName() - selecting elements by tag name, live HTMLCollections, and modern alternatives.

Syntax

const elements = document.getElementsByTagName(tagName);
// Returns a LIVE HTMLCollection

Basic Examples

// Get all paragraphs
const paragraphs = document.getElementsByTagName('p');
console.log(paragraphs.length);  // count of <p> elements

// Access by index
const first = paragraphs[0];
const last = paragraphs[paragraphs.length - 1];

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

// Get ALL elements
const allElements = document.getElementsByTagName('*');

// Scoped search (within a specific element)
const nav = document.getElementById('main-nav');
const navLinks = nav.getElementsByTagName('a');

Live HTMLCollection

The returned HTMLCollection is live - it automatically updates when the DOM changes. This can cause unexpected behavior in loops:

const divs = document.getElementsByTagName('div');
console.log(divs.length);  // e.g., 5

// Add a new div
document.body.appendChild(document.createElement('div'));
console.log(divs.length);  // 6 - collection updated automatically!

// DANGER: infinite loop when removing elements
const items = document.getElementsByTagName('li');
// WRONG - collection shrinks as you remove, skips elements
for (let i = 0; i < items.length; i++) {
  items[i].remove();  // items.length changes each iteration!
}

// CORRECT - iterate backwards
for (let i = items.length - 1; i >= 0; i--) {
  items[i].remove();
}

// ALSO CORRECT - convert to static array first
const staticItems = [...document.getElementsByTagName('li')];
staticItems.forEach(item => item.remove());

Iterating

const links = document.getElementsByTagName('a');

// for loop (classic)
for (let i = 0; i < links.length; i++) {
  console.log(links[i].href);
}

// for...of (modern)
for (const link of links) {
  link.style.color = 'blue';
}

// Convert to array for .map(), .filter(), .forEach()
const hrefs = Array.from(links).map(a => a.href);
const external = [...links].filter(a =>
  a.hostname !== location.hostname
);

Comparison Table

MethodReturnsLive?Selector
getElementsByTagName()HTMLCollectionYesTag name
getElementsByClassName()HTMLCollectionYesClass name
querySelectorAll()NodeListNo (static)Any CSS selector
querySelector()Element | nullN/AAny CSS selector
getElementById()Element | nullN/AID

When to use: Prefer querySelectorAll() for most use cases. Use getElementsByTagName() when you specifically need a live collection that updates as the DOM changes, or when working with legacy code.

Last updated: 2026 • Browse all courses