Get the First/Last element with specific Class name in JS

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
4 min

banner

# Table of Contents

  1. Get the First element with a specific Class name in JS
  2. Get the Last element with a specific Class name in JS

# Get the First element with a specific Class name in JS

Use the querySelector() method to get the first element with a specific class name, e.g. document.querySelector('.box').

The method returns the first element that matches the provided selector or null if no element matches.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const first = document.querySelector('.box'); console.log(first); // ๐Ÿ‘‰๏ธ div.box console.log(first.textContent); // ๐Ÿ‘‰๏ธ "Box 1"

get first element with specific class name

The code for this article is available on GitHub

The document.querySelector() method takes a string that is a valid CSS selector as a parameter.

The method returns the first element in the document that matches the provided selector or null if no element matches.

Alternatively, you could use the getElementsByClassName() method to get an HTMLCollection of the matching elements and access the element at index 0 to get the first element with the specified class.

index.js
const first = document.getElementsByClassName('box')[0]; console.log(first); // ๐Ÿ‘‰๏ธ div.box

Notice that the document.getElementsByClassName() method takes the class name and not a selector as a parameter.

If no elements with the provided class name exist in the DOM, an empty HTMLCollection is returned.

If you are unable to find the element you are looking for, use the getElementsByClassName() method to get a collection of all elements with the specific class name and iterate over the collection looking for the element.

index.js
const boxes = document.getElementsByClassName('box'); let element; for (const box of boxes) { if (box.textContent.toLowerCase() === 'box 1') { console.log('โœ… box found'); element = box; break; } } console.log(element); // ๐Ÿ‘‰๏ธ div.box console.log(element.textContent); // ๐Ÿ‘‰๏ธ "Box 1"
The code for this article is available on GitHub

We used the for...of loop to iterate over the collection of elements with the class box.

On each iteration, we check if the element has a text content of box 1. If the condition is met, we assign the element to a variable.

When the element is found, use the break keyword to break out of the for loop to avoid doing unnecessary work.

# Get the Last element with a specific Class name in JS

To get the last element with a specific class name:

  1. Use the querySelectorAll() method to get a NodeList containing the elements with the specific class.
  2. Convert the NodeList to an array.
  3. Use the pop() method to get the last element of the array.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const last = Array.from( document.querySelectorAll('.box') ).pop(); console.log(last); // ๐Ÿ‘‰๏ธ div.box console.log(last.textContent); // ๐Ÿ‘‰๏ธ "Box 3"

get last element with specific class name

The code for this article is available on GitHub

The document.querySelectorAll() method takes a string that contains a valid CSS selector as a parameter and returns a NodeList containing the matching elements.

We used the Array.from method to convert the NodeList to an array, so we can use the Array.pop() method.

The pop method removes the last element from an array and returns it.

You could use the document.getElementsByClassName() method to achieve the same result.

index.js
const last = Array.from( document.getElementsByClassName('box') ).pop(); console.log(last); // ๐Ÿ‘‰๏ธ div.box console.log(last.textContent); // ๐Ÿ‘‰๏ธ "Box 3"

The getElementsByClassName() method takes a class name as a parameter and returns an HTMLCollection that contains the matching elements.

This approach might be a little faster than using the querySelectorAll method, but querySelectorAll is more flexible because it can be passed a CSS selector and not just a class name.

If you can't find the element you are looking for, use the getElementsByClassName() method to get a collection of all elements with the specific class name and iterate over the collection looking for the specific element.

index.js
const boxes = document.getElementsByClassName('box'); let element; for (const box of boxes) { if (box.textContent.toLowerCase() === 'box 3') { console.log('โœ… box found'); element = box; break; } } console.log(element); // ๐Ÿ‘‰๏ธ div.box console.log(element.textContent); // ๐Ÿ‘‰๏ธ "Box 3"
The code for this article is available on GitHub

We used the for...of loop to iterate over the collection of elements with the class box.

On each iteration, we check if the element has a text content of box 1, and if the condition is met, we assign the element to a variable.

When the element is found, use the break keyword to break out of the for loop and avoid doing unnecessary work.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev