JavaScript Element getElementsByClassName() Method

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

What You’ll Learn

Element.getElementsByClassName() is an instance method that finds descendant elements matching one or more class names and returns a live HTMLCollection. Learn scoped searches, multiple classes, live-collection pitfalls, comparison with querySelectorAll(), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

HTMLCollection

03

Args

class names

04

Scope

Descendants

05

Live

Auto-updates

06

Status

Baseline widely

Introduction

When you need every element with a certain CSS class inside a section of the page, getElementsByClassName() is a direct, readable option. It searches only descendants of the element you call it on—not the element itself.

The return value is a live HTMLCollection. If matching elements are added or removed from the subtree, the collection updates automatically (MDN).

💡
Beginner tip

Modern code often uses querySelectorAll('.class'), which returns a static NodeList. Prefer getElementsByClassName() when you want a live collection, or when you already have a parent element and a simple class lookup.

This page is part of JavaScript Element. Document.getElementsByClassName() works the same way from the document root (MDN).

Understanding the getElementsByClassName() Method

Calling el.getElementsByClassName(names) walks the subtree under el and collects every descendant whose class list matches names.

  • It is an instance method on Element.
  • names — one or more class names, whitespace-separated (MDN).
  • Returns a live HTMLCollection.
  • Multiple classes mean the element must include all of them.
  • Case-sensitive in standards mode; case-insensitive in quirks mode (MDN).
  • Also available on Document for whole-page searches (MDN).

📝 Syntax

General form of Element.getElementsByClassName (MDN):

JavaScript
getElementsByClassName(names)

Parameters

names — a string containing one or more class names to match, separated by whitespace.

Return value

A live HTMLCollection of every descendant element that is a member of every class in names (MDN).

Common patterns

JavaScript
// Single class
const items = container.getElementsByClassName("item");

// Multiple classes (must have both)
const cards = container.getElementsByClassName("card featured");

// Scoped under #main (MDN)
const tests = document.getElementById("main")
  .getElementsByClassName("test");

// Access items
console.log(items.length);
console.log(items[0]);

⚡ Quick Reference

GoalCode
Find by one classel.getElementsByClassName("item")
Multiple classesel.getElementsByClassName("a b")
Scoped searchparent.getElementsByClassName("x")
Count matchescollection.length
Static alternativeel.querySelectorAll(".item")
MDN statusBaseline Widely available (since October 2017)

🔍 At a Glance

Four facts to remember about Element.getElementsByClassName().

Returns
HTMLCollection

Live list

Baseline
widely

Since Oct 2017

Scope
descendants

Subtree only

Modern
querySelAll

Static alt

📋 Class lookup APIs

getElementsByClassName()querySelectorAll()getElementsByTagName()
ReturnsLive HTMLCollectionStatic NodeListLive HTMLCollection
SelectorClass names onlyFull CSS selectorTag name only
Updates on DOM changeYes (live)No (snapshot)Yes (live)
Best forSimple class lookupsComplex selectorsTag-based collections
On DocumentYesYesYes

Examples Gallery

Examples follow MDN Element.getElementsByClassName() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN: match a single class name inside an element subtree.

Example 1 — Single Class

Find all descendants with class item.

JavaScript
const container = document.getElementById("list");
const items = container.getElementsByClassName("item");

console.log(items.length);
console.log(items[0].textContent);
Try It Yourself

How It Works

The search runs only on descendants of container, not on container itself unless it also has the class.

Example 2 — Scoped Search Under #main

MDN: limit results to descendants of a specific element.

JavaScript
const main = document.getElementById("main");
const tests = main.getElementsByClassName("test");

console.log(tests.length);
// Only .test elements inside #main
Try It Yourself

How It Works

Elements with class test outside #main are not included. This is useful for component-scoped DOM queries.

📈 Practical Patterns

Multiple classes, live-collection loops, and filtering results.

Example 3 — Multiple Classes

MDN: pass "red test" to match elements that have both classes.

JavaScript
const boxes = container.getElementsByClassName("red test");

console.log(boxes.length);
// Elements with class="red test" (both required)
Try It Yourself

How It Works

Whitespace separates class names. Order does not matter; the element must include every name you pass.

Example 4 — Live Collection Loop (MDN)

When removing a class inside a forward loop, use while (matches.length).

JavaScript
const matches = element.getElementsByClassName("color-box");

while (matches.length > 0) {
  matches.item(0).classList.add("hue-frame");
  matches[0].classList.remove("color-box");
}
Try It Yourself

How It Works

MDN: a for loop with i++ skips elements because the live collection shrinks when you remove the matching class. Always process item(0) or copy to a static array first.

Example 5 — Filter with Array Methods (MDN)

Keep only DIV elements from the collection.

JavaScript
const testElements = document.getElementsByClassName("test");

const testDivs = Array.prototype.filter.call(
  testElements,
  (el) => el.nodeName === "DIV"
);

console.log(testDivs.length);
Try It Yourself

How It Works

MDN: pass the HTMLCollection as this to Array.prototype.filter.call. You can also spread into an array: [...testElements].

🚀 Common Use Cases

  • Selecting all cards, list items, or buttons sharing a CSS class.
  • Scoped queries inside a widget or component root element.
  • Live dashboards that react when matching nodes are added dynamically.
  • Bulk class toggling on a set of descendant elements.
  • Teaching the difference between live collections and static NodeLists.
  • Legacy codebases that predate widespread querySelectorAll usage.

🧠 How getElementsByClassName() Finds Matches

1

Pass class name(s)

getElementsByClassName("item") or "red test"

Args
2

Walk descendant subtree

Browser scans every descendant of the element you called it on.

Search
3

Return live HTMLCollection

Matching elements appear and disappear as the DOM changes (MDN).

Result
4

Use or modernize

For complex selectors use querySelectorAll; copy to an array when mutating during loops.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, October 2017).
  • Returns a live HTMLCollection, not a static snapshot.
  • Multiple class names must all be present on the element.
  • Searches descendants only—the element you call it on is not included.
  • Case-sensitive in standards mode; case-insensitive in quirks mode (MDN).
  • Related: closest(), getClientRects(), JavaScript hub.

Browser Support

Element.getElementsByClassName() is Baseline Widely available (MDN: across browsers since October 2017). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.getElementsByClassName()

Find descendant elements by class with a live HTMLCollection — scope searches to any element subtree.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Supported in legacy IE
Yes
getElementsByClassName() Excellent

Bottom line: Use getElementsByClassName() for simple class lookups in a subtree. Remember the collection is live — copy to an array or use while(matches.length) when mutating during loops.

Conclusion

Element.getElementsByClassName() returns a live HTMLCollection of descendant elements matching the class names you pass. It is a straightforward way to query by class within any element subtree.

Continue with closest(), getClientRects(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Scope searches to a parent element when possible
  • Use while (collection.length) when removing matches in a loop
  • Copy to an array ([...collection]) for safe iteration
  • Pass multiple classes as one whitespace-separated string
  • Prefer querySelectorAll for complex CSS selectors

❌ Don’t

  • Assume the collection is static like querySelectorAll
  • Use a forward for loop while removing matching classes
  • Forget descendants-only — the caller element is not included
  • Pass CSS selectors with dots (".item") — use plain class names
  • Rely on case-insensitivity unless you are in quirks mode

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.getElementsByClassName()

Live class-based descendant search.

5
Core concepts
📄 02

Live

auto-update

DOM
✍️ 03

Scope

descendants

Subtree
04

Baseline

widely available

Status
05

Modern

querySelAll

Static

❓ Frequently Asked Questions

It returns a live HTMLCollection of descendant elements whose class list includes the specified class name or names. The search is limited to the subtree rooted at the element you call it on.
No. MDN marks Element.getElementsByClassName() as Baseline Widely available (across browsers since October 2017). It is not Deprecated, Experimental, or Non-standard.
A string with one or more class names separated by whitespace. With multiple names, elements must include every listed class (MDN).
getElementsByClassName() returns a live HTMLCollection that updates when the DOM changes. querySelectorAll() returns a static NodeList snapshot.
Yes. MDN: matching elements are added or removed from the collection immediately when the DOM subtree changes.
Yes. Document.getElementsByClassName() works the same way but searches from the document root. Element.getElementsByClassName() searches only descendants of that element.
Did you know?

MDN notes that the returned HTMLCollection is live: when you add or remove matching elements from the subtree, the collection updates immediately. That is the main difference from querySelectorAll().

More Element Topics

Browse Element methods and properties to keep building your DOM skills.

closest() →

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.

8 people found this page helpful