Reputation: 1167
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
?
Upvotes: 21
Views: 50627
Reputation: 2944
Follow these Steps:
var elems = document.querySelectorAll(".some-element");
var len = elems.length;
var lastelement = len < 1 ? "" : elems[len-1];
Upvotes: 4
Reputation: 684
querySelectorAll
returns NodeList
object which can be converted to Array
. Then pop
returns the last element.
Array.from(document.querySelectorAll('.some-element')).pop();
function addItem(withClass){
document.body.insertAdjacentHTML('beforeend', withClass
? '<div class="some-element">with class</div>'
: '<div>without class</div>'
)
findLastOfClass('.some-element')
}
function findLastOfClass(selector){
var lastOfClass = [...document.querySelectorAll(selector)].pop()
// temporarily highlight last-of-class
if( lastOfClass ){
lastOfClass.classList.add('highlight')
setTimeout(()=> lastOfClass.classList.remove('highlight'), 1000)
}
}
.highlight{ background: lightyellow }
<button onClick="addItem(true)">add item with class</button>
<button onClick="addItem()">add item without class</button>
Array.prototype.pop.call(document.querySelectorAll('.some-element'));
Upvotes: 11
Reputation: 15293
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])
Upvotes: 37
Reputation: 1356
To find the last child of an element you can use this:
var childrenCount = document.getElementById("myDIV").childNodes.length;
document.getElementById("myDIV").childNodes[childrenCount-1];
Upvotes: 5