Get the Last element with specific Class name using JS

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

Get the Last element with specific Class name using JS #

To get the last element with 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 examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <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>

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"

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"

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.