Javascipt DOM getElementsByClassName
The getElementsByClassName
method in JavaScript is used to access all elements with a specified class name. Unlike getElementById
, which returns a single element, getElementsByClassName
returns a live HTMLCollection
of elements.
Syntax
const elements = document.getElementsByClassName(className);
Parameters
className
: A string representing the class name to match. You can specify one or more class names separated by spaces. Note that the method matches elements with all specified class names, not just one.
Return Value
- Returns an
HTMLCollection
of elements with the specified class name(s). This collection is live, meaning it automatically updates when elements with the specified class name(s) are added or removed from the document.
Usage
Selecting Elements
To get all elements with a specific class name:
<!DOCTYPE html> <html> <head> <title>getElementsByClassName Example</title> <style> .highlight { color: red; } </style> </head> <body> <p class="highlight">Paragraph 1</p> <p>Paragraph 2</p> <p class="highlight">Paragraph 3</p> <button onclick="highlightText()">Highlight Text</button> <script> function highlightText() { // Get all elements with class 'highlight' const elements = document.getElementsByClassName('highlight'); // Loop through the HTMLCollection and change text color for (let i = 0; i < elements.length; i++) { elements[i].style.color = 'blue'; } } </script> </body> </html>
In this example, clicking the button will change the text color of all paragraphs with the
highlight
class to blue.Modifying Elements
You can loop through the
HTMLCollection
to modify the properties of each element:const elements = document.getElementsByClassName('highlight'); for (let i = 0; i < elements.length; i++) { // Change text content elements[i].textContent = 'Updated text!'; // Add a new class elements[i].classList.add('new-class'); // Remove the existing class elements[i].classList.remove('highlight'); }
Live Collection
The
HTMLCollection
returned bygetElementsByClassName
is live, meaning it updates automatically:const elements = document.getElementsByClassName('highlight'); console.log(elements.length); // Initially logs the number of elements with class 'highlight' // Dynamically add a new element with the class 'highlight' const newElement = document.createElement('p'); newElement.className = 'highlight'; newElement.textContent = 'New highlighted paragraph'; document.body.appendChild(newElement); console.log(elements.length); // Now logs the updated number of elements, including the new one
Limitations
- Live Collection: The live nature of the
HTMLCollection
means it reflects changes to the DOM, which can sometimes lead to unexpected results if not handled carefully. - No Direct Query: Unlike
querySelectorAll
,getElementsByClassName
doesn’t support complex CSS selectors or pseudo-classes. It only matches elements based on class names.
- Live Collection: The live nature of the
Best Practices
- Class Name Uniqueness: Avoid using class names that are too generic to prevent unexpected selections.
- Iterating Through Collections: Always iterate through the
HTMLCollection
using a loop to apply changes to all matched elements. - Handling Live Collections: Be cautious when working with live collections, especially if you plan to make changes to the DOM that might affect the collection.