telebog
telebog

Reputation: 1896

Accessing the last input element of a form

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

Answers (3)

Kijewski
Kijewski

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';

http://jsfiddle.net/zUVg5/

Upvotes: 5

Anthony Grist
Anthony Grist

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

Travis J
Travis J

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

Related Questions