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
?
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];
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.
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-element
simply do
var someElementsItems = document.querySelectorAll(".some-element");
console.log(someElementsItems[someElementsItems.length -1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With