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?
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.
print(a[1]) #prints second item in list print(a[-1]) #prints the last item in the list.
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');
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