Edgars Šturms Edgars Šturms - 1 year ago 58
Javascript Question

Shortest way to get last element by class name in javascript

I know that by using

you can easily use
selector to get the last element.


Although, this does not work with javascript.


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


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

Answer Source

Take a look at the Selectors Overview


an E element, last child of its parent

  <li class="some-element">1</li>
  <li class="some-element">2</li>
  <li class="some-element">3</li>


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


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]);
  <li class="some-element">1</li>
  <li class="some-element">2</li>
  <li class="some-element">3</li>

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])