How to Get the First or Last Element with a Specific Class in JavaScript
When working with the DOM, you often need to select a specific element from a group of elements that share the same class. Common tasks include getting the first item in a list, the last card in a gallery, or targeting a specific instance of a component.
This guide will teach you the modern, standard methods for getting both the first and the last element that has a specific CSS class, using the powerful querySelector and querySelectorAll methods.
The Modern Method: querySelector and querySelectorAll
These two methods are the "Swiss Army knife" of modern DOM selection. They are flexible, powerful, and use standard CSS selector syntax.
document.querySelector('selector'): Returns the first element in the document that matches the selector.document.querySelectorAll('selector'): Returns a staticNodeListcontaining all elements that match the selector.
To select by a class name, you use the standard CSS dot (.) notation (e.g., .my-class).
We'll use this simple list for our examples.
<div class="item">Item 1</div>
<div class="item featured">Item 2</div>
<div class="item">Item 3</div>
Goal 1: Get the First Element with a Specific Class
If you only need the very first element on the page that matches your class, the querySelector() method is the perfect tool.
For example, we want to get the first div with the class item.
The recommended solution is to use querySelector that automatically stops searching after it finds the first match. This makes the solution both concise and efficient.
const firstItem = document.querySelector('.item');
console.log(firstItem.textContent); // Output: "Item 1"
This is the simplest and most direct way to get the first matching element.
Goal 2: Get the Last Element with a Specific Class
Getting the last element requires a slightly different approach, as there is no queryLastSelector. Instead, we get all matching elements and then take the last one from that collection.
For example, we want to get the last div with the class item.
The recommended solution consist to:
- Use
querySelectorAll()to get aNodeListof all matching elements. - Access the last element of the
NodeListusing itslengthproperty.
const allItems = document.querySelectorAll('.item');
// A NodeList is array-like, so we can access elements by index.
// The last element's index is always length - 1.
const lastItem = allItems[allItems.length - 1];
console.log(lastItem.textContent); // Output: "Item 3"
This is the most common and readable way to get the last element.
A concise alternative
You can also use Array.from() to convert the NodeList to a true array and then use the .pop() method to get the last element. This is a clever one-liner, but it's slightly less performant as it creates an intermediate array.
const lastItem = Array.from(document.querySelectorAll('.item')).pop();
A Note on the Older getElementsByClassName Method
Before querySelector was common, the standard was getElementsByClassName().
const items = document.getElementsByClassName('item');
const firstItem = items[0];
Why querySelector is Generally Better:
- More Flexible:
querySelectorcan handle any CSS selector (.class,#id,[attribute],div > p), whereasgetElementsByClassNameonly works for classes. - Consistency: Using
querySelectorandquerySelectorAllfor all your queries provides a single, consistent API for DOM selection. - Static
NodeList:querySelectorAllreturns a staticNodeList, whilegetElementsByClassNamereturns a liveHTMLCollection, which can have performance implications and lead to unexpected behavior if the DOM is modified while you are iterating over it.
For these reasons, querySelector and querySelectorAll are the recommended best practices in modern web development.
Conclusion
Selecting the first or last element with a specific class is a simple task with modern DOM APIs.
- To get the first element, the most direct and efficient method is
document.querySelector('.your-class'). - To get the last element, the standard method is to use
document.querySelectorAll('.your-class')to get all matching elements and then access the last one from the resultingNodeList.
By using these powerful and flexible methods, you can write clean and readable code to select any element you need.