检查元素是否为div

93

如何检查$(this)divulblockquote

例如:

if ($(this) is a div) {
  alert('its a div!');
} else {
  alert('its not a div! some other stuff');
}
11个回答

146

类似这样:

if(this.tagName == 'DIV') {
    alert("It's a div!");
} else {
    alert("It's not a div! [some other stuff]");
}

4
你知道吗,$(this).get(0) 相当于 this 但没有额外的开销。 - Mic
3
@Bjorn 对,this 也不是。$(this).get(0) 接受 this(一个普通的 JS DOM 节点),将其转换为 jQuery 对象,运行 .get(0),选择 jQuery 对象中的第一个常规 DOM 节点...也就是将您带回到起点。this.tagName = $(this)[0].tagName = $(this).get(0).tagName - brymck
13
@Bryan,人们只想到jQuery而不是JavaScript,这太令人震惊了。 - Mic
1
当你知道类型时,三个等号更加正确 :) - Ben
6
需要提醒使用 .toLowerCase(),以防 JavaScript 随机返回大写名称,即使名称在 HTML 中是小写的。 - Buffalo
显示剩余4条评论

48

已经发布了不使用jQuery的解决方案,所以我将发布使用jQuery的解决方案。

$(this).is("div,ul,blockquote")

22

检查此元素是否为 DIV

if (this instanceof HTMLDivElement) {
   alert('this is a div');
}

对于无序列表,使用HTMLUListElement;对于引用块,使用HTMLQuoteElement


TypeScript的好方法! - Илья Зеленько
1
如果您使用了iframe等,请注意。每个窗口都有自己的类,因此即使元素是DIV,但来自不同的窗口,这也会返回false。 - waterplea

21

没有使用jQuery时,可以使用this.tagName === 'DIV'来判断。

记住tagName中的'N'是大写。

或者,对于更多的标签:

/DIV|UL|BLOCKQUOTE/.test(this.tagName)


5
if(this.tagName.toLowerCase() == "div"){
    //it's a div
} else {
    //it's not a div
}

编辑:在我写作的过程中,很多答案已经给出了,对于重复回答感到抱歉。


1
不对。$(this).tagName 是完全错误的。你的意思是 $(this).attr('tagName') - Marco Faustinelli

5

虽然这是一个老问题,但由于没有任何答案提到这一点,一个现代的替代方案,不需要使用jquery,只需使用CSS选择器和 Element.matches(),就可以实现。

element.matches('div, ul, blockquote');


3

通过jQuery,您可以使用$(this).is('div')

针对选择器、元素或jQuery对象检查当前匹配的元素集,并在至少有一个元素与给定参数相匹配时返回true。


2

有些解决方案有点过头了。你只需要使用普通的JavaScript中的tagName就可以了。重新用jQuery包装整个内容并运行库中一些更强大的函数来检查标签名称,实际上并没有任何好处。如果你想在此页面上测试它,这里有一个例子。

$("body > *").each(function() {
  if (this.tagName === "DIV") {
    alert("Yeah, this is a div");
  } else {
    alert("Bummer, this isn't");
  }
});

1
let myElement =document.getElementById("myElementId");

if(myElement.tagName =="DIV"){

  alert("is a div");

}else{

  alert("is not a div");

}
/*What ever you may need to know the type write it in capitalised letters "OPTIO" ,"PARAGRAPH", "SPAN" AND whatever */

准确地说,大写字母 - Fanky

1
我正在增强Andreq Frenkel的答案,想要添加一些内容,结果变得太冗长了所以放在这里...
考虑到CustomElements扩展现有元素并且仍然能够检查一个元素是否为例如input,让我觉得instanceof是解决这个问题的最佳方案。
不过,应该注意到instanceof使用引用相等性,因此父窗口中的HTMLDivElement与其iframe(或者影子DOM等)中的不同。
为了处理这种情况,应该使用被检查元素所属窗口的类,像这样: element instanceof element.ownerDocument.defaultView.HTMLDivElement

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接