javascript 如何按名称获取html元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3856697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a html element by name
提问by Harshana
Is there a way in java script to get only a particular name instead of using document.getElementsByName("x");which return an array? I have a kind of special situation where i can't use the id. Any suggestions please?
Thank You.
java脚本中有没有办法只获取一个特定的名称而不是使用document.getElementsByName("x");哪个返回一个数组?我有一种特殊情况,我不能使用 id。请问有什么建议吗?谢谢。
回答by Quentin
Just get the first element:
只需获取第一个元素:
document.getElementsByName("x")[0];
Or for safety:
或者为了安全:
function getFirstElementByName(element_name) {
var elements = document.getElementsByName(element_name);
if (elements.length) {
return elements[0];
} else {
return undefined;
}
}
(BTW getElementsByName returns a collection, not an array.)
(顺便说一句,getElementsByName 返回一个集合,而不是一个数组。)
回答by Nick Craver
If you're looking for a single element, take the first one from the nodelist, for example:
如果您要查找单个元素,请从节点列表中获取第一个元素,例如:
var element = document.getElementsByName("x")[0];
回答by Ricardo Otero
Or use jQuery, so you don't have to bother with all the browser annoyance.
或者使用jQuery,这样您就不必为所有浏览器烦恼而烦恼。
You just have to do this:
你只需要这样做:
$("*[name='x']").first();
To get the first element with that name. If you know the element type than you can use it instead of "*". jQuery will make your life easier every time!
获取具有该名称的第一个元素。如果您知道元素类型,则可以使用它代替“*”。jQuery 每次都会让您的生活更轻松!

