Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  124] [ 3]  / answers: 1 / hits: 18430  / 9 Years ago, fri, february 5, 2016, 12:00:00

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?


More From » javascript

 Answers
62

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 as the8472's answer suggests would be


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

[#63428] Wednesday, February 3, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leannjaidynd

Total Points: 111
Total Questions: 100
Total Answers: 94

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
leannjaidynd questions
Thu, Mar 18, 21, 00:00, 3 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Mon, May 11, 20, 00:00, 4 Years ago
Tue, Feb 4, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;