JavaScript Document getElementsByClassName() Method

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

What You’ll Learn

document.getElementsByClassName() is an instance method that returns every element with the given class name(s) (see MDN Document: getElementsByClassName()). Learn the live HTMLCollection, multiple class matching, element-scoped searches, how it compares to querySelectorAll, and five try-it labs.

01

Kind

Instance method

02

Arg

class name(s)

03

Returns

HTMLCollection

04

Live?

Yes

05

Multi-class

all required

06

Status

Baseline

Introduction

When several elements share a class — cards, buttons, list items — getElementsByClassName collects them all in one array-like list.

MDN: the method returns an array-like object of all child elements that have all of the given class name(s). On document, the whole document is searched (including the root). You can also call it on any element to search only that subtree.

💡
Think: live group photo of matching classes

1) Pass "test" or "red test"
2) Get a live HTMLCollection
3) Read [0], length, or loop with for...of
4) Remember: DOM changes update the collection automatically

⚠️
Live collection warning (MDN)

This is a live HTMLCollection. If an element stops matching (for example you remove its class), it disappears from the list. Be careful when iterating and mutating at the same time.

Related tutorials: getElementById(), getAnimations(), getElementsByName().

Understanding document.getElementsByClassName()

An instance method on document (and also on elements) from the Document interface (MDN).

  • names — string of one or more class names, separated by whitespace (MDN).
  • Return value — a live HTMLCollection of found elements (MDN).
  • All classes required — with multiple names, the element must have every class (MDN).
  • Document scope — searches the complete document when called on document (MDN).
  • Element scope — on an element, only descendants of that root match (MDN).
  • Not a real Array — array-like; use Array.from or Array.prototype helpers when needed (MDN).

📝 Syntax

General form of Document.getElementsByClassName (MDN):

JavaScript
getElementsByClassName(names)

Parameters

  • names — a string representing the class name(s) to match; multiple class names are separated by whitespace (MDN).

Return value

A live HTMLCollection of found elements (MDN).

MDN quick samples

JavaScript
document.getElementsByClassName("test");
document.getElementsByClassName("red test");
document.getElementById("main").getElementsByClassName("test");
document.getElementsByClassName("test")[0];

⚡ Quick Reference

GoalCode
One classdocument.getElementsByClassName("test")
Both classesdocument.getElementsByClassName("red test")
First matchdocument.getElementsByClassName("test")[0]
Inside a rootdocument.getElementById("main").getElementsByClassName("test")
To ArrayArray.from(document.getElementsByClassName("test"))
MDN statusBaseline Widely available (since Jul 2015)

🔍 At a Glance

Four facts about document.getElementsByClassName().

Returns
HTMLCollection

live

Arg
names

string

Multi
all classes

required

Status
Baseline

since 2015

📋 Live collection vs static snapshot

Live HTMLCollectionStatic NodeList (querySelectorAll)
After DOM changeList updates automatically (MDN)Stays as captured at query time
Remove matching classElement drops out of the collection (MDN)Still in the old NodeList
Iteration tipCopy to an array if you mutate while loopingSafer for one-pass mutations

Examples Gallery

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

📚 Getting Started

Collect elements that share a class.

Example 1 — All elements with class test

MDN’s simplest call; read length and the first item.

JavaScript
const list = document.getElementsByClassName("test");
console.log(list.length);
console.log(list[0] && list[0].textContent);
Try It Yourself

How It Works

The result is not a single element — it is a collection. Use [0] when you want the first match (MDN).

Example 2 — Multiple classes (all required)

MDN: only elements that have every listed class are selected.

JavaScript
const matches = document.getElementsByClassName("orange juice");
for (const el of matches) {
  console.log(el.textContent);
}
// Similar idea: document.querySelectorAll(".orange.juice")
Try It Yourself

How It Works

"orange juice" is not “orange OR juice” — it is elements that have both classes, like CSS .orange.juice (MDN).

📈 Practical Patterns

Scoped roots, live updates, and Array helpers.

Example 3 — Search inside a parent

MDN: call the method on an element to limit the search.

JavaScript
const parentDOM = document.getElementById("parent-id");
const test = parentDOM.getElementsByClassName("test");
const testTarget = test[0];
console.log(test.length);
console.log(testTarget && testTarget.textContent);
Try It Yourself

How It Works

Unlike getElementById, class lookup works on any element root. MDN reminds you that the collection is a list, not the element itself.

Example 4 — Live collection updates

Remove a class and watch length shrink without re-querying.

JavaScript
const cards = document.getElementsByClassName("card");
console.log("before:", cards.length);

cards[0].classList.remove("card");
console.log("after:", cards.length); // live list updated (MDN)
Try It Yourself

How It Works

MDN warning: when an element no longer qualifies, it is automatically removed from the collection. That is powerful — and easy to miss during loops.

Example 5 — Filter with Array.prototype

MDN pattern: treat the collection as this for Array methods.

JavaScript
const testElements = document.getElementsByClassName("test");
const testDivs = Array.prototype.filter.call(
  testElements,
  (testElement) => testElement.nodeName === "DIV",
);
console.log(testDivs.length);
// Or: Array.from(testElements).filter(...)
Try It Yourself

How It Works

HTMLCollection is array-like but not a real Array. MDN shows borrowing filter; Array.from is often clearer today.

🚀 Common Use Cases

  • Style batches — highlight every .active item.
  • Event wiring — attach listeners to all .btn elements.
  • Scoped widgets — search only inside a panel with an element root.
  • Multi-class filters — require both tag and selected.
  • Prefer querySelectorAll — for complex selectors or static snapshots.
  • Not unique ids — use getElementById() for one id.

🧠 How getElementsByClassName() Works

1

Pass class name string(s)

One name, or several whitespace-separated names (MDN).

Input
2

Search document or subtree

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

Scope
3

Match all required classes

With multiple names, every class must be present (MDN).

Filter
4

Live HTMLCollection

Index, loop, or convert to an array; DOM changes keep it updated.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • MDN: returns a live HTMLCollection — watch iteration while mutating.
  • MDN: multiple class names require all of them on the element.
  • MDN: callable on document or on any element for a scoped search.
  • Not a true Array — use Array.from or borrowed Array methods (MDN).
  • Related: getElementById(), getAnimations(), getElementsByName().

Browser Support

Document.getElementsByClassName() 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.getElementsByClassName()

Live HTMLCollection of elements matching one or more class names 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
getElementsByClassName() Wide

Bottom line: Use getElementsByClassName for simple class lookups. Prefer querySelectorAll for complex selectors or a static NodeList.

Conclusion

document.getElementsByClassName(names) gathers every matching element into a live HTMLCollection. Pass one class or several (all required), optionally scope to a parent element, and remember the list updates as the DOM changes.

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

💡 Best Practices

✅ Do

  • Remember the result is a collection, not a single element (MDN)
  • Use multiple class names when you need an AND match
  • Scope searches with an element root when possible
  • Copy to an array before mutating while iterating
  • Reach for querySelectorAll for richer selectors

❌ Don’t

  • Treat the return value as one element without [0]
  • Forget the collection is live (MDN warning)
  • Expect "a b" to mean a OR b — it means both
  • Assume Array methods exist without Array.from / borrowing
  • Use class lookups when a unique id is the right tool

Key Takeaways

Knowledge Unlocked

Five things to remember about getElementsByClassName()

Live class matches as an HTMLCollection.

5
Core concepts
🔄02

Live

auto-updates

warning
🎯03

Multi

all classes

AND
04

Scope

doc or element

MDN
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.getElementsByClassName() returns an array-like object of all child elements that have all of the given class name(s). On document, it searches the complete document.
No. MDN marks Document.getElementsByClassName() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A live HTMLCollection of found elements (MDN). Changes in the DOM are reflected in the collection as they occur.
MDN: pass a whitespace-separated string. Only elements that have ALL of those classes are selected (similar idea to .orange.juice in querySelectorAll).
Yes. MDN: you may call getElementsByClassName() on any element; it returns only matching descendants of that root.
Prefer querySelectorAll when you need more complex CSS selectors, a static NodeList snapshot, or modern Array methods without Array.prototype.call tricks.
Did you know?

MDN’s multiple-class demo pairs getElementsByClassName("orange juice") with querySelectorAll(".orange.juice") — two spellings of the same “must have both classes” idea.

Next: getElementsByName()

Learn how to collect every element that shares a name attribute into a live NodeList.

getElementsByName() →

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