JavaScript Document getElementsByTagName() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.getElementsByTagName() is an instance method that returns every element with a given tag name (see MDN Document: getElementsByTagName()). Learn the live HTMLCollection, the * wildcard, element-scoped searches, how it compares to querySelectorAll, and five try-it labs.

01

Kind

Instance method

02

Arg

tag name / *

03

Returns

HTMLCollection

04

Live?

Yes

05

Order

tree order

06

Status

Baseline

Introduction

Need every <p>, <li>, or <img> on the page? Pass the tag name to document.getElementsByTagName() and get a live list.

MDN: the method returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node. The collection is live — it stays in sync with the DOM without calling the method again.

💡
Think: “give me all paragraphs”

1) Call document.getElementsByTagName("p")
2) Get a live HTMLCollection in tree order
3) Read length, [0], or loop
4) Or pass "*" to match every element (MDN)

📄
Document vs Element (MDN)

document.getElementsByTagName() searches the whole document. Element.getElementsByTagName() is functionally identical but starts at a specific parent — perfect for counting tags inside one panel.

Related tutorials: getElementsByName(), getElementsByClassName(), getElementsByTagNameNS().

Understanding document.getElementsByTagName()

An instance method on the Document interface (MDN). The same idea also exists on elements for scoped searches.

  • name — tag name string; * means all elements (MDN).
  • Return value — a live HTMLCollection in tree order (MDN).
  • Whole document — search includes the root node (MDN).
  • Element scope — call on a parent to search only descendants (MDN).
  • HTML lowercasing — on HTML documents the argument is lower-cased (MDN).
  • SVG tip — for camel-case SVG tags, prefer getElementsByTagNameNS() (MDN).

📝 Syntax

General form of Document.getElementsByTagName (MDN):

JavaScript
getElementsByTagName(name)

Parameters

  • name — a string representing the name of the elements. The special string * represents all elements (MDN).

Return value

A live HTMLCollection of found elements in the order they appear in the tree (MDN).

MDN quick samples

JavaScript
const allParas = document.getElementsByTagName("p");
const everything = document.getElementsByTagName("*");
const div1Paras = document.getElementById("div1").getElementsByTagName("p");

⚡ Quick Reference

GoalCode
All paragraphsdocument.getElementsByTagName("p")
All elementsdocument.getElementsByTagName("*")
First matchdocument.getElementsByTagName("img")[0]
Inside a parentdocument.getElementById("div1").getElementsByTagName("p")
To ArrayArray.from(document.getElementsByTagName("li"))
MDN statusBaseline Widely available (since Jul 2015)

🔍 At a Glance

Four facts about document.getElementsByTagName().

Returns
HTMLCollection

live

Arg
name

tag / *

Scope
doc or el

MDN

Status
Baseline

since 2015

📋 Document search vs element search

document.getElementsByTagNameelement.getElementsByTagName
Start pointWhole document (MDN)That element’s descendants (MDN)
Includes root?Document search includes root node (MDN)Descendants of the element
Return typeLive HTMLCollectionLive HTMLCollection
MDN demo ideaCount all <p> tagsCount <p> inside #div1 / #div2

Examples Gallery

Examples follow MDN Document: getElementsByTagName() and practical beginner patterns.

📚 Getting Started

Collect every element of a given tag.

Example 1 — Count all <p> elements

MDN’s classic document-wide paragraph count.

JavaScript
const allParas = document.getElementsByTagName("p");
const num = allParas.length;
console.log(`There are ${num} paragraph in this document`);
Try It Yourself

How It Works

The collection is ordered as elements appear in the tree (MDN). Use length for a quick count without converting to an array.

Example 2 — Search inside a parent

MDN: start from a specific element with Element.getElementsByTagName().

JavaScript
const div1 = document.getElementById("div1");
const div1Paras = div1.getElementsByTagName("p");
console.log(`There are ${div1Paras.length} paragraph in #div1`);

const div2 = document.getElementById("div2");
const div2Paras = div2.getElementsByTagName("p");
console.log(`There are ${div2Paras.length} paragraph in #div2`);
Try It Yourself

How It Works

Nested parents count differently: paragraphs inside #div2 also count toward #div1 because they are descendants (MDN demo idea).

📈 Practical Patterns

Wildcard matching, live updates, and batch styling.

Example 3 — Wildcard * for all elements

MDN: * represents all elements.

JavaScript
const all = document.getElementsByTagName("*");
console.log(all.length);
console.log(all[0] && all[0].tagName);
Try It Yourself

How It Works

Use * sparingly on large pages — it can be a long live list. Prefer a specific tag when you already know the element type.

Example 4 — Live collection updates

Append another matching tag and watch length grow without re-querying.

JavaScript
const list = document.getElementsByTagName("li");
console.log("before:", list.length);

const extra = document.createElement("li");
extra.textContent = "New item";
document.querySelector("ul").appendChild(extra);

console.log("after:", list.length); // live list updated (MDN)
Try It Yourself

How It Works

MDN: the returned HTMLCollection updates itself automatically to stay in sync with the DOM tree.

Example 5 — Style every matching tag

Loop the collection and apply a shared style to each match.

JavaScript
const imgs = document.getElementsByTagName("img");
for (const img of imgs) {
  img.style.border = "2px solid teal";
}
console.log("styled:", imgs.length);
Try It Yourself

How It Works

Tag-based batches are great for simple UI sweeps. For class-based groups, prefer getElementsByClassName().

🚀 Common Use Cases

  • Count tags — how many paragraphs or images exist?
  • Scoped widgets — only tags inside a panel or card.
  • Batch updates — style or read every matching tag.
  • Live dashboards — keep a length counter as the DOM changes.
  • Prefer querySelectorAll — for complex selectors or static snapshots.
  • SVG namespaces — use getElementsByTagNameNS() for camel-case SVG (MDN).

🧠 How getElementsByTagName() Works

1

Pass a tag name (or *)

Examples: "p", "img", or "*" for everything (MDN).

Input
2

Search document or subtree

On document: whole tree. On an element: descendants only (MDN).

Scope
3

Match tags in tree order

Results appear in the order they exist in the DOM (MDN).

Order
4

Live HTMLCollection

Index, loop, or convert; DOM changes keep the list updated.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • MDN: returns a live HTMLCollection in tree order.
  • MDN: * matches all elements.
  • MDN: on HTML documents the argument is lower-cased before matching.
  • MDN: for camel-case SVG in HTML, prefer getElementsByTagNameNS().
  • Related: getElementsByName(), getElementsByClassName(), getElementsByTagNameNS().

Browser Support

Document.getElementsByTagName() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.getElementsByTagName()

Live HTMLCollection of elements matching a tag name across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
getElementsByTagName() Wide

Bottom line: Use getElementsByTagName for simple tag lists. Prefer querySelectorAll for complex selectors or a static NodeList.

Conclusion

document.getElementsByTagName(name) gathers every matching tag into a live HTMLCollection. Pass a tag name or *, optionally scope to a parent element, and remember the list stays synced as the DOM changes.

Continue with getElementsByName(), getElementsByTagNameNS(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use a specific tag when you know the element type
  • Scope searches with an element root for local counts (MDN)
  • Remember the collection is live and ordered by the tree (MDN)
  • Convert with Array.from when you need Array helpers
  • Reach for getElementsByTagNameNS for camel-case SVG (MDN)

❌ Don’t

  • Treat the return value as one element without [0]
  • Forget HTML lowercases the argument (MDN)
  • Overuse * on huge documents without need
  • Assume Array methods exist without converting first
  • Skip querySelectorAll when you need complex CSS filters

Key Takeaways

Knowledge Unlocked

Five things to remember about getElementsByTagName()

Live tag matches as an HTMLCollection.

5
Core concepts
🔄02

Live

auto-updates

MDN
🎯03

Wildcard

* = all

MDN
04

Scope

doc or element

MDN
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.getElementsByTagName() returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node.
No. MDN marks Document.getElementsByTagName() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A live HTMLCollection of found elements in the order they appear in the tree (MDN). It updates automatically as the DOM changes.
MDN: the special string * represents all elements.
Yes. MDN: Element.getElementsByTagName() is functionally identical but starts the search at a specific element in the DOM tree.
MDN: on an HTML document, getElementsByTagName() lower-cases its argument. For camel-case SVG elements, use document.getElementsByTagNameNS().
Did you know?

MDN’s nested #div1 / #div2 demo shows that paragraphs inside the inner box still count toward the outer box — because getElementsByTagName walks all descendants, not just direct children.

Next: getElementsByTagNameNS()

Learn how to collect elements by namespace URI and local name — especially useful for SVG.

getElementsByTagNameNS() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful