JavaScript getElementsByClassName

Usage:

The getElementsByClassName() method is a powerful tool in the DOM API used to select every element in a document that possesses a specific CSS class. Unlike getElementById, which targets a single unique element, this method is designed for "bulk" selection. Whether you are building a list of interactive cards, a set of navigation links, or a group of form inputs, this method allows you to grab them all at once.

Developer Tip: While you often call this on the document object to search the whole page, you can also call it on a specific element to search only within that element's children. This is great for keeping your code scoped and efficient.

Syntax:

// Selecting from the entire document
const elements = document.getElementsByClassName(className);

// Selecting from within a specific parent element
const parent = document.getElementById('sidebar');
const menuItems = parent.getElementsByClassName('nav-link');
  • className: A string representing the class name you want to match. Note that you do not include a dot (.) like you would in a CSS selector.
Common Mistake: Including a period before the class name (e.g., getElementsByClassName('.my-class')). This will result in no elements being found. Simply use the name: 'my-class'.

Return Value:

  • The method returns a live HTMLCollection. This is an array-like object containing all found elements in the order they appear in the source code.
  • If no matching elements are found, the method returns an empty HTMLCollection with a length of 0.
Best Practice: Because an HTMLCollection is "array-like" but not a true Array, it lacks modern methods like .forEach(), .map(), or .filter(). Convert it to a real array using Array.from(elements) or the spread operator [...elements] to use these helpful methods.

Example:

Imagine you have a list of tasks and you want to highlight all tasks marked as "urgent."

<!-- HTML Structure -->
<div class="task urgent">Pay Rent</div>
<div class="task">Buy Groceries</div>
<div class="task urgent">Fix Server Bug</div>
// JavaScript Implementation
const urgentTasks = document.getElementsByClassName('urgent');

for (let i = 0; i < urgentTasks.length; i++) {
    urgentTasks[i].style.color = 'red';
    urgentTasks[i].style.fontWeight = 'bold';
}

console.log(urgentTasks.length); // Output: 2

Accessing Elements:

  • Index Notation: You access individual elements just like an array, using square brackets: elements[0].
  • Iteration: Since it has a length property, you can use a standard for loop to iterate through the collection.

Live Collection:

One of the most unique features of getElementsByClassName is that the collection is live. This means if the DOM changes, the collection updates itself automatically without you needing to call the method again.

Watch Out: Being "live" can be dangerous. If you are looping through a collection and removing the class name you searched for, the element will vanish from the collection immediately. This can cause your loop to skip elements or end prematurely.

Null Handling:

  • Unlike querySelector, which returns null if nothing is found, getElementsByClassName() always returns a collection object. To check if anything was found, always check the .length property.

Browser Support:

  • getElementsByClassName() is highly reliable and supported in all modern browsers, including Internet Explorer 9 and above. It is significantly faster than querySelectorAll in many performance benchmarks.

 

Key Points

  • Group Selection: Ideal for selecting multiple elements that share a specific class for bulk styling or event listeners.
  • Speed: It is one of the fastest ways to query the DOM, especially in large documents.
  • Live Updating: The returned HTMLCollection reflects the current state of the DOM in real-time.
  • Array-like: Remember to convert it to a standard Array if you need to use modern functional programming methods.