Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last item from node list without using .length

Tags:

javascript

The following command

document.querySelectorAll('#divConfirm table')[1].querySelectorAll('tr')

gives a node list with 3 tablerow (tr) elements in it. If I know the list size, I can access the last element via.item(2).

Is there a way to get the last element directly without resorting to .length first?

like image 335
Doug Fir Avatar asked Feb 05 '16 18:02

Doug Fir


People also ask

How do I get the last element of an array?

To get the last item in an array when you don't know the length of that array: const lastItem = animals[animals. length - 1] ; The lastItem variable now holds the value of horse.

How do you print the last element of a list in Python?

print(a[1]) #prints second item in list print(a[-1]) #prints the last item in the list.


1 Answers

There's at least one way

var els = document.querySelectorAll('#divConfirm table')[1].querySelectorAll('tr');

var last = [].slice.call(els).pop();

but, the following statement

But if I do not know the length prior to running the script

makes no sense, you already have the collection of elements, so you would always know the length

var els = document.querySelectorAll('#divConfirm table')[1].querySelectorAll('tr');

var last = els[els.length - 1];

Another option would be

document.querySelector('#divConfirm table:nth-child(2) tr:last-child');
like image 109
adeneo Avatar answered Nov 16 '22 23:11

adeneo