Reputation: 1896
In an HTML document I have a form and from the form there are several input elements (not a fix number). I want to get the last input element.
I tried:
imputs=document.getElementsByTagName('input');
lastIndex=imputs.length;
imputs[lastIndex] - here I get undefined
I don't understand why the following code works and the previous not:
lastIndex=10;
imputs[lastIndex]
Upvotes: 2
Views: 3588
Reputation: 26022
imputs = document.getElementsByTagName('input');
lastIndex = imputs.length;
imputs[lastIndex - 1]
Arrays ([upd.] and NodeList, etc.) are 0 based in JavaScript.
Also: i*n*puts. ;)
An alternative method would be document.querySelector('...') with ":last-of-type":
document.querySelector('input:last-of-type').value = '42';
Upvotes: 5
Reputation: 38345
The getElementsByTagName()
function returns a NodeList
containing all of the elements that have the specified tag name. These elements can be accessed using the square bracket notation by specifying an index.
However, elements in the list are indexed from 0 to N, where N is one less than the length of the list. In order to get the last element, you actually want imputs[imputs.length - 1];
.
Upvotes: 2
Reputation: 82287
Arrays are zero based. Length will give you an item which is undefined because it is after the end of the array. You should use
imputs[lastIndex - 1]
Upvotes: 1