Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to get last element by class name in javascript

Tags:

javascript

dom

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?

like image 885
Mr. Blond Avatar asked Aug 30 '16 09:08

Mr. Blond


People also ask

How do you get the first element of getElementsByClassName?

If you want only the first element in the DOM with that class, you can select the first element out of the array returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0];

How do I select the first child in querySelector?

The querySelector() method returns the first child element that matches a specified CSS selector(s) of an element. Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead.


1 Answers

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])
like image 60
DavidDomain Avatar answered Oct 04 '22 18:10

DavidDomain