Javascript

How to Get Element By Class in JavaScript

19 September 2026 · 10 min read

How to Get Element By Class in JavaScript

JavaScript is a powerful language for manipulating web pages, and a fundamental skill for any web developer is knowing how to get element by class. This seemingly simple task is crucial for dynamically updating content, applying styles, and responding to user interactions. Imagine you have multiple elements on a webpage, all sharing the same class, and you need to modify all of them at once. Perhaps you want to change their text color, hide them, or attach event listeners. Understanding how to effectively select these elements using their class name is paramount to achieving this. This article dives deep into the various methods available in JavaScript to get element by class, providing detailed explanations, practical examples, and best practices to help you master this essential skill. We’ll explore the nuances of each method, discuss their performance implications, and provide real-world scenarios where they shine. By the end of this guide, you’ll be well-equipped to efficiently and accurately target elements based on their class names in your JavaScript code.

Understanding getElementsByClassName()

The getElementsByClassName() method is a core function in the Document Object Model (DOM) that allows you to retrieve all elements in a document that have a specific class name. This method returns a live HTMLCollection, meaning that any changes to the DOM that add or remove elements with the specified class will automatically update the collection. This is an important distinction compared to methods like querySelectorAll(), which returns a static NodeList. The syntax is straightforward: document.getElementsByClassName(‘className’). It’s important to remember that getElementsByClassName() is a method of the document object, meaning you call it directly on the document to search the entire document or on a specific element to search within that element’s descendants.

For example, let’s say you have several

elements with the class name "highlight": html
This is highlighted.
This is also highlighted.
And this paragraph too!

You can retrieve all these elements using the following JavaScript code:

javascript const highlightedElements = document.getElementsByClassName(‘highlight’); console.log(highlightedElements); // Output: HTMLCollection [div.highlight, div.highlight, p.highlight] This code will return an HTMLCollection containing all three elements. You can then iterate through this collection to perform actions on each element. As mentioned earlier, this collection is live, so if you dynamically add another element with the class “highlight” to the DOM, it will automatically be included in the highlightedElements collection.

One key consideration is browser compatibility. While getElementsByClassName() is widely supported in modern browsers, older versions of Internet Explorer may have limited support. For maximum compatibility, consider using a polyfill or alternative methods, especially when targeting older browsers. Understanding the “live” nature of the HTMLCollection and browser compatibility are crucial aspects of effectively using getElementsByClassName(). According to a study by StatCounter, browser compatibility issues, although diminishing, still account for a fraction of website errors, highlighting the need for backward compatibility strategies. StatCounter provides valuable data on browser usage and compatibility trends.

Exploring querySelectorAll()

The querySelectorAll() method offers a more versatile and powerful way to get element by class, along with other CSS selectors. Unlike getElementsByClassName(), which only accepts a class name as an argument, querySelectorAll() accepts any valid CSS selector, including IDs, attributes, and pseudo-classes. This flexibility makes it a preferred choice for complex element selection scenarios. The method returns a static NodeList, meaning that the list of elements is fixed at the time of the query and does not update automatically with changes to the DOM. This can be both an advantage (for predictable results) and a disadvantage (if you need a live collection).

To select elements by class using querySelectorAll(), you simply use the dot (.) notation, just like in CSS. For example:

javascript const highlightedElements = document.querySelectorAll(’.highlight’); console.log(highlightedElements); // Output: NodeList [div.highlight, div.highlight, p.highlight] This code will return a NodeList containing all elements with the class “highlight,” identical to the output of the getElementsByClassName() example. However, querySelectorAll()’s power lies in its ability to combine class selectors with other selectors. For instance, you can select all

elements with the class "highlight" using: javascript const highlightedDivs = document.querySelectorAll('div.highlight'); console.log(highlightedDivs); // Output: NodeList [div.highlight, div.highlight] This will return only the two
elements with the class "highlight," excluding the element. This level of specificity is not possible with getElementsByClassName(). Furthermore, querySelectorAll() can be used to select elements based on other attributes, IDs, or pseudo-classes. This makes it a much more flexible and powerful tool for element selection in JavaScript. The featured snippet below highlights the key advantages of using querySelectorAll():

querySelectorAll() offers greater flexibility than getElementsByClassName() by accepting any valid CSS selector, including IDs, attributes, and pseudo-classes. This allows for more specific and complex element selection, making it a preferred choice for many developers when needing to get element by class or using more advanced selection criteria.

Performance Considerations: getElementsByClassName() vs. querySelectorAll()

While querySelectorAll() offers greater flexibility, it’s important to consider performance implications. In general, getElementsByClassName() is often faster than querySelectorAll(), especially in older browsers. This is because getElementsByClassName() is a native method optimized for specifically selecting elements by class name. querySelectorAll(), on the other hand, needs to parse a CSS selector, which can be more computationally expensive. However, in modern browsers, the performance difference is often negligible, and the added flexibility of querySelectorAll() outweighs the slight performance cost. It’s advised to benchmark in your specific use case if performance is critical. According to research by Google, optimizing JavaScript execution time can significantly improve page load speed and user experience. Google’s web.dev provides extensive resources on web performance optimization.

Iterating Through the Results

Once you’ve retrieved the elements using either getElementsByClassName() or querySelectorAll(), you’ll typically want to iterate through the resulting collection to perform some action on each element. Both HTMLCollection and NodeList objects can be iterated using standard JavaScript loops.

Here’s how you can iterate through an HTMLCollection using a for loop:

javascript const highlightedElements = document.getElementsByClassName(‘highlight’); for (let i = 0; i < highlightedElements.length; i++) { highlightedElements[i].style.color = ‘red’; } This code will change the text color of all elements with the class “highlight” to red. Similarly, you can iterate through a NodeList using a for loop:

javascript const highlightedElements = document.querySelectorAll(’.highlight’); for (let i = 0; i < highlightedElements.length; i++) { highlightedElements[i].style.color = ‘red’; } Alternatively, you can use the forEach() method, which is available on NodeList objects (but not directly on HTMLCollection objects in all browsers). To use forEach() with an HTMLCollection, you can convert it to an array first:

javascript const highlightedElements = document.getElementsByClassName(‘highlight’); Array.from(highlightedElements).forEach(element => { element.style.color = ‘red’; }); Or, more simply using the spread operator:

javascript const highlightedElements = document.getElementsByClassName(‘highlight’); […highlightedElements].forEach(element => { element.style.color = ‘red’; }); The forEach() method provides a more concise and readable way to iterate through the elements. Choose the iteration method that best suits your needs and coding style. Remember to consider browser compatibility when choosing between for loops and forEach(). It is also important to understand that HTMLCollection is a live collection. Be careful modifying the DOM within a loop iterating through an HTMLCollection, as it can lead to unexpected behavior.

Best Practices and Common Pitfalls

When working with getElementsByClassName() and querySelectorAll(), it’s important to follow best practices to ensure your code is efficient, maintainable, and robust. Here are some key recommendations:

  • Use specific selectors: Avoid using overly broad selectors, as this can lead to performance issues. Be as specific as possible to target only the elements you need.
  • Cache the results: If you need to access the same elements multiple times, store the results of getElementsByClassName() or querySelectorAll() in a variable to avoid repeatedly querying the DOM.
  • Consider performance: Be mindful of the performance implications of each method, especially when working with large documents or complex selectors. Benchmark your code if performance is critical.

Here are some common pitfalls to avoid:

  • Forgetting the live nature of HTMLCollection: Be aware that HTMLCollection objects are live, and changes to the DOM can affect the collection. This can lead to unexpected behavior if you’re not careful.
  • Incorrect selector syntax: Ensure that your CSS selectors are valid, especially when using querySelectorAll(). Incorrect syntax can lead to unexpected results or errors.
  • Browser compatibility issues: Be aware of browser compatibility issues, especially when targeting older browsers. Use polyfills or alternative methods to ensure your code works across different browsers.
Infographic here
Let’s consider a real-world scenario: Imagine a website with a dynamic theme switcher. When the user selects a different theme, you need to update the styles of all elements with a specific class, such as "theme-element." By using getElementsByClassName() or querySelectorAll(), you can easily select all these elements and apply the new theme styles. This demonstrates the practical application of these methods in creating dynamic and interactive web experiences.

To reiterate, consider the following steps when attempting to get element by class in JavaScript:

  1. Identify the target class: Determine the specific class name you want to use to select elements.
  2. Choose the appropriate method: Select either getElementsByClassName() or querySelectorAll() based on your needs. If you only need to select elements by class name and performance is critical, use getElementsByClassName(). If you need more flexibility with CSS selectors, use querySelectorAll().
  3. Retrieve the elements: Call the selected method on the document object or a specific element to retrieve the elements.
  4. Iterate through the results: Use a for loop or the forEach() method to iterate through the resulting collection.
  5. Perform actions on each element: Apply the desired actions to each element in the collection, such as changing its style, content, or attributes.

FAQ

**What is the difference between getElementsByClassName() and querySelectorAll()?**
getElementsByClassName() only accepts a class name as an argument and returns a live HTMLCollection. querySelectorAll() accepts any valid CSS selector and returns a static NodeList.
**Which method is faster, getElementsByClassName() or querySelectorAll()?**
Generally, getElementsByClassName() is faster, especially in older browsers. However, the performance difference is often negligible in modern browsers.
**How do I iterate through an HTMLCollection?**
You can iterate through an HTMLCollection using a for loop or by converting it to an array and using the forEach() method.
**How do I iterate through a NodeList?**
You can iterate through a NodeList using a for loop or the forEach() method.
**Can I use querySelectorAll() to select elements by ID?**
Yes, you can use querySelectorAll() to select elements by ID using the hash () notation (e.g., document.querySelectorAll('myElement')).
Mastering the art of selecting elements by class in JavaScript is an essential skill for any web developer. By understanding the nuances of getElementsByClassName() and querySelectorAll(), along with their respective strengths and weaknesses, you can write more efficient, maintainable, and robust code. Remember to consider the specific requirements of your project, the performance implications of each method, and the importance of following best practices. With this knowledge, you'll be well-equipped to tackle any element selection challenge that comes your way. [Continue expanding your JavaScript knowledge](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c) and explore related topics such as event handling, DOM manipulation **Question & Answer :**

I want to replace the contents within a html element so I’m using the following function for that:

function ReplaceContentInContainer(id,content) { var container = document.getElementById(id); container.innerHTML = content; } ReplaceContentInContainer('box','This is the replacement text'); <div id='box'></div> 

The above works great but the problem is I have more than one html element on a page that I want to replace the contents of. So I can’t use ids but classes instead. I have been told that javascript does not support any type of inbuilt get element by class function. So how can the above code be revised to make it work with classes instead of ids?

P.S. I don’t want to use jQuery for this.

This code should work in all browsers.

function replaceContentInContainer(matchClass, content) { var elems = document.getElementsByTagName('*'), i; for (i in elems) { if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ') > -1) { elems[i].innerHTML = content; } } } 

The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.

jsFiddle Example, using Vanilla JS (i.e. no framework)