Edgars Šturms Edgars Šturms - 3 months ago 20
Javascript Question

Shortest way to get last element by class name in javascript

I know that by using

jQuery
you can easily use
:last
selector to get the last element.

$(".some-element:last")


Although, this does not work with javascript.

document.querySelectorAll(".some-element:last")


What would be the best and shortest way to do the same thing in
javascript
?

Edit:

I don't have a wrapper element with
id
attribute, that's way I cannot use
lastChild
.

Answer

Take a look at the Selectors Overview

E:last-child

an E element, last child of its parent

console.log(document.querySelectorAll(".some-element:last-child"))
<ul>
  <li class="some-element">1</li>
  <li class="some-element">2</li>
  <li class="some-element">3</li>
</ul>

--Update--

If you have additional elements that do not share the same class name you can try a different approach like using

E:nth-last-of-type(n)

an E element, the n-th sibling of its type, counting from the last one

var lastLiItem = document.querySelectorAll("li:nth-last-of-type(1)");
var lastSomeElement = document.querySelectorAll("li:nth-last-of-type(2)");

console.log("This is the last li item in the list: ", lastLiItem[0]);
console.log("This is the last li item with class .some-element in the list: ", lastSomeElement[0]);
<ul>
  <li class="some-element">1</li>
  <li class="some-element">2</li>
  <li class="some-element">3</li>
  <li>4</li>
</ul>

Or to only get the last element with class of .some-elementsimply do

var someElementsItems = document.querySelectorAll(".some-element");
console.log(someElementsItems[someElementsItems.length -1])