Get last item from node list without using .length

Next command

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

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

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

+4
source share
3 answers

There is at least one way

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

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

but the next statement

But if I do not know the length before running the script

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

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

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

Another variant:

document.querySelector('#divConfirm table:nth-child(2) tr:last-child');
+5
source

depending on the circumstances, this may work: document.querySelector('#divConfirm table tr:last-of-type')

+1
source
0

Source: https://habr.com/ru/post/1627495/


All Articles