The getElementsByClassName() method is a high-performance DOM interface that allows you to select all elements in a document that possess one or more specific CSS class names. As a core part of the web’s original selection API, it is highly optimized by browser engines, making it significantly faster than more versatile methods like querySelectorAll().

1. Syntax and Basic Mechanism

The method can be called on the global document object to search the entire page or on a specific element to search only within that element’s descendants.

JavaScript
const elements = rootElement.getElementsByClassName(names);

Parameters

names (Required): A string containing one or more class names.

  • To select elements with multiple classes, separate the names with spaces (e.g., “btn primary”). This will only match elements that have both classes.
  • In HTML documents, this search is case-sensitive.

Return Value

  • HTMLCollection: Returns a live, ordered collection of elements.
  • Empty Collection: If no matches are found, it returns an HTMLCollection with a .length of 0 (it never returns null).

2. Practical Examples

A. Global Class Selection

This is commonly used to apply bulk logic to UI components, such as closing all open modals.

JavaScript
const modals = document.getElementsByClassName('modal-window');

for (let i = 0; i < modals.length; i++) {
  modals[i].style.display = 'none';
}

B. Selection with Multiple Classes

You can narrow your search to elements that must satisfy several class conditions simultaneously.

JavaScript
// Matches <button class="btn active login-type"> but NOT <button class="btn">
const activeLoginButtons = document.getElementsByClassName('btn active');

C. Scoped Selection

Searching within a specific container prevents your script from accidentally affecting other parts of the page.

JavaScript
const sidebar = document.getElementById('sidebar-menu');
const menuItems = sidebar.getElementsByClassName('menu-item');

3. The “Live” Nature of the Collection

A critical characteristic of getElementsByClassName() is that it returns a Live HTMLCollection. Unlike a static NodeList (returned by querySelectorAll), a live collection automatically updates itself whenever the DOM changes.

The Side-Effect Risk

Because the collection is live, modifying the classes of the elements as you loop through them can lead to unexpected behavior. For example, if you remove a class that you are currently selecting by, the element will immediately vanish from the collection, causing your loop index to skip the next item.

JavaScript
const highlights = document.getElementsByClassName('highlight');

// ❌ WARNING: This loop may skip every second element!
for (let i = 0; i < highlights.length; i++) {
  highlights[i].classList.remove('highlight'); 
}

Solution: Loop backward (for (let i = highlights.length - 1; i >= 0; i--)) or convert the collection to a static array first.

4. Working with HTMLCollections

An HTMLCollection is an array-like object, but it is not a true JavaScript Array. It lacks modern methods like .map(), .filter(), or .forEach().

Accessing Elements

You can access elements by index or by their id or name attribute:

JavaScript
const buttons = document.getElementsByClassName('action-btn');
const firstBtn = buttons[0];          // By Index
const submitBtn = buttons['submit']; // By ID or Name

Conversion to Array

To use functional programming methods, convert the collection using the spread operator or Array.from():

JavaScript
const items = [...document.getElementsByClassName('list-item')];

items.filter(el => el.textContent.includes('Urgent'))
     .forEach(el => el.classList.add('priority'));

5. Advanced Usage: Logic and Filtered Iteration

Because the collection is indexed, you can target the first or last instance of a class with high efficiency. This is often used for “active state” management where you need to move a class from one element to the next.

JavaScript
function moveActiveState(newElement) {
  const currentActive = document.getElementsByClassName('active');
  
  // If an active element exists, remove the class
  if (currentActive.length > 0) {
    currentActive[0].classList.remove('active');
  }
  
  // Add active class to the new target
  newElement.classList.add('active');
}

Categorized in:

JS DOM,