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
3 Answers
Reset to default 5imputs = 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
版权声明:本文标题:javascript - Accessing the last input element of a form - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744255335a2597451.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论