- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
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.
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.
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
HTMLCollectionwith alengthof 0.
.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
lengthproperty, you can use a standardforloop 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.
Null Handling:
- Unlike
querySelector, which returnsnullif nothing is found, getElementsByClassName() always returns a collection object. To check if anything was found, always check the.lengthproperty.
Browser Support:
- getElementsByClassName() is highly reliable and supported in all modern browsers, including Internet Explorer 9 and above. It is significantly faster than
querySelectorAllin 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
HTMLCollectionreflects 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.