jQuery 什么类型的 DOM 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6114683/
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-26 20:25:26  来源:igfitidea点击:

What type of DOM Element?

jqueryhtmldom

提问by murvinlai

e.g. if i have this:
<div id='mydiv'>whatever</div>

then let say in jQuery, how can I find out that the dom element with id "mydiv" is a DIV or is some other element type.

然后让我们在 jQuery 中说,我怎么能找出 ID 为“mydiv”的 dom 元素是 DIV 还是其他元素类型。

e.g. 
$('#mydiv').????  ?

回答by John Strickler

var type = $('#mydiv')[0].tagName

alert(type);
//displays "DIV"

回答by Michael Haren

Try iswhich tests if anything in the given set matches another selector:

尝试is测试给定集合中的任何内容是否与另一个选择器匹配:

if( $('#mydiv').is('div') ){
  // it's a div
}

You can also get the tag this way:

您还可以通过以下方式获取标签:

$('#mydiv').get(0).tagName // yields: 'DIV'

回答by Shaz

alert($('#mydiv')[0].nodeName);

回答by James Hymanson

The .prop()function is a nice way of doing this.

.prop()函数是这样做的一个很好的方式。

// Very jQuery
$('#mydiv').prop('tagName');

// Less jQuery
$('#mydiv')[0].tagName;

Both give the same result.

两者都给出相同的结果。

And, as Aram Kocharyan commented, you'll probably want to standardise it with .toLowerCase().

而且,正如 Aram Kocharyan 评论的那样,您可能希望使用.toLowerCase().

回答by Doug Stephen

$('#mydiv').get(0).nodeTypeif you know there's only one element. The selector object can contain an array of objects.

$('#mydiv').get(0).nodeType如果你知道只有一个元素。选择器对象可以包含一个对象数组。

.get()returns the array of DOM objects, the parameter indexes. nodeTypeis a property exposed by the DOM that tells you what the type of the DOM node is. Usually as a String in all caps IIRC.

.get()返回 DOM 对象数组,参数索引。 nodeType是 DOM 公开的属性,它告诉您 DOM 节点的类型是什么。通常作为所有大写 IIRC 中的字符串。

CORRECTIONnodeTypegives you an INT corresponding to a nodeType. tagNameis what you want.

CORRECTIONnodeType为您提供与 nodeType 对应的 INT。 tagName是你想要的。

回答by Ross

var domElement = $('#mydiv').get(0);
alert(domElement .tagName);

may be of use.

可能有用。