Javascript 获取 getElementsByName 返回的对象的标签名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6342687/
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
get the tag name of object returned by getElementsByName
提问by kamikaze_pilot
so suppose I call document.getElementsByName("title");
in javascript
所以假设我调用document.getElementsByName("title");
javascript
and I want to know the type of the tag of the element that is returned by that function, for instance, to see if it's a meta tag or a div tag or a span tag, etc
我想知道该函数返回的元素标签的类型,例如,看看它是元标签还是 div 标签或 span 标签等
how would I go about doing this?
我该怎么做呢?
回答by venimus
document.getElementsByName("title");
returns a set of elements not a single element
so within a cycle you could use element.tagName
to get the tag
document.getElementsByName("title");
返回一组元素而不是单个元素,因此在一个循环内您可以element.tagName
用来获取标签
basicly
基本上
document.getElementsByName("title")[0].tagName
should work
document.getElementsByName("title")[0].tagName
应该管用
回答by James Westgate
You have returned a NodeList
object, so you would need to be more specific with your selector, or choose the first element using an index of 0, as in the other answers.
您已经返回了一个NodeList
对象,因此您需要更具体地使用选择器,或者像其他答案一样使用索引 0 选择第一个元素。
Whilst you can use nodeName
or tagName
, nodeName
is the better option.
虽然您可以使用nodeName
或tagName
,但这nodeName
是更好的选择。
回答by James Allardice
You can use the tagName
property like so:
您可以tagName
像这样使用该属性:
document.getElementsByName('name')[index].tagName;
document.getElementsByName('name')[index].tagName;
You need the index as the getElementsByName
function returns an array.
您需要索引,因为该getElementsByName
函数返回一个数组。