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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:19:44  来源:igfitidea点击:

get the tag name of object returned by getElementsByName

javascripthtmldommeta-tags

提问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.tagNameto get the tag

document.getElementsByName("title");返回一组元素而不是单个元素,因此在一个循环内您可以element.tagName用来获取标签

basicly

基本上

document.getElementsByName("title")[0].tagNameshould work

document.getElementsByName("title")[0].tagName应该管用

回答by James Westgate

You have returned a NodeListobject, 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 nodeNameor tagName, nodeNameis the better option.

虽然您可以使用nodeNametagName,但这nodeName是更好的选择。

回答by James Allardice

You can use the tagNameproperty like so:

您可以tagName像这样使用该属性:

document.getElementsByName('name')[index].tagName;

document.getElementsByName('name')[index].tagName;

You need the index as the getElementsByNamefunction returns an array.

您需要索引,因为该getElementsByName函数返回一个数组。