我正在使用 document.getElementsByTagName("input") 来获取我表单中的所有输入元素。在遍历它们时,我需要找到一个具有特定 id 的元素说“数据”并处理它。如何搜索存在特定 id 的元素的元素。
最佳答案
如果出于某些原因您不想这样做:
var el = document.getElementById('data');
...您可以遍历集合:
var inputs = document.getElementsByTagName("input"),
len = inputs.length,
el;
while( len-- ) {
if( inputs[ len ].id === 'data' ) { // Test the "id" property.
el = inputs[ len ]; // If a match, grab that one,
break; // and break the loop.
}
}
编辑: 修复了我使用 el = inputs[ len ].id;
而不是 el = inputs[ len ];
的错误/p>
关于javascript - javascript的元素id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4637503/