admin管理员组

文章数量:1405557

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]

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]
Share Improve this question edited Feb 21, 2013 at 21:34 MikeM 27.4k4 gold badges67 silver badges80 bronze badges asked Feb 21, 2013 at 21:31 telebogtelebog 1,9065 gold badges26 silver badges37 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5
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/zUVg5/

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];.

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]

本文标签: javascriptAccessing the last input element of a formStack Overflow