Javascript 检查元素是否为div

Javascript 检查元素是否为div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,如何检查$(this)是否为div、ul或块报价 例如: if ($(this) is a div) { alert('its a div!'); } else { alert('its not a div! some other stuff'); } 没有jQuery,您可以说this.tagName==='DIV' 请记住,标记名中的“N”是大写的 或者,使用更多标记: /DIV | UL | BLOCKQUOTE/.test(this.tagName)类似以下内容: if(thi

如何检查
$(this)
是否为
div
ul
块报价

例如:

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

没有jQuery,您可以说
this.tagName==='DIV'

请记住,
标记名
中的“N”是大写的

或者,使用更多标记:

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

类似以下内容:

if(this.tagName==“DIV”){
警惕(“这是一个div!”);
}否则{
警惕(“这不是一个div![其他东西]”);
}

通过jQuery,您可以使用:

根据选择器、元素或jQuery对象检查当前匹配的元素集,如果这些元素中至少有一个与给定参数匹配,则返回true


尝试使用不带jQuery的解决方案,因为已经发布了,所以我将使用jQuery发布解决方案

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

编辑:当我写作时,给出了很多答案,很抱歉Doubule

有些解决方案有点过火了。您所需要的只是来自常规旧JavaScript的
标记名
。再次在jQuery中重新包装整个内容,尤其是运行库中一些更强大的函数来检查标记名,并不会给您带来任何好处。如果您想在此页面上测试它,下面是一个示例

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

检查此元素是否为DIV

if (this instanceof HTMLDivElement) {
   alert('this is a div');
}
对于UL,
HtmlListElement
与之相同,

HTMLQuoteElement
对于blockquote

我正在增强Andreq Frenkel的答案,只是想添加一些,它变得太长了,所以就到此为止

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 */
考虑到CustomElements扩展了现有的元素,并且仍然能够检查元素是否是,比如说,
input
,我认为
instanceof
是解决这个问题的最佳方法

但是,应该注意,
的instanceof
使用引用相等,因此父窗口的
htmldevelment
将与其
iframe
中的一个窗口(或阴影DOM等)不同

要处理这种情况,应该使用checked元素自己的窗口类,例如:


element.ownerDocument.defaultView.htmldevelment的element instanceof element.ownerDocument.htmldevelment

这是一个老问题,但由于没有任何答案提到这一点,没有jquery的现代替代方案可能只是使用CSS选择器和


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

您知道
$(this).get(0)
this
等效,但没有开销吗?@Bjorn对,而且
this
也不是
$(this).get(0)
获取
this
(普通JS DOM节点),将其转换为jQuery对象,运行
.get(0)
,选择jQuery对象中的第一个常规DOM节点。。。也就是说,带你回到你开始的地方
this.tagName=$(this)[0]。tagName=$(this).get(0)。tagName
@Bryan,人们在jQuery中的思维方式令人震惊,而不再是在jQuery中Javascript@Bjorn:这当然不行。在您的示例中,您传递了一个字符串(选择器),但在回答中,
this
已经是一个DOM元素。只要尝试
this==$(this).get(0)
。值得提醒使用.toLowerCase(),以防javascript决定随机返回大写名称,即使名称在html.Nope中是小写的<代码>$(此).tagName完全错误。你的意思是
$(this).attr('tagName')
打字脚本的好方法!如果你有iFrame之类的东西,小心使用它。每个窗口都有自己的类,因此即使元素是DIV,也会返回false,但来自不同的窗口。确切地说,是大写
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 */