检查,如果元素是div

Jam*_*mes 59 html javascript css jquery

我如何检查是否$(this)div,ulblockquote

例如:

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

Bjo*_*orn 92

像这样的东西:

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

  • @Bryan,令人震惊的是人们如何在jQuery中思考,而不再是Javascript (8认同)
  • 或者只是`this.tagName`. (4认同)
  • 你知道`$(this).get(0)`相当于`this`但没有开销吗? (4认同)
  • @Bjorn对,也不是'this`.`$(this).get(0)`接受`this`(一个普通的JS DOM节点),将它转换为jQuery对象,运行`.get(0)`,它选择jQuery对象中的第一个常规DOM节点......也就是说,带你回到你开始的地方.`this.tagName = $(this)[0] .tagName = $(this).get(0).tagName`. (3认同)
  • 值得提醒使用.toLowerCase(),以防javascript决定随机返回大写名称,即使名称是html中的小写. (3认同)

MBO*_*MBO 42

没有jQuery的解决方案已经发布,所以我将使用jQuery发布解决方案

$(this).is("div,ul,blockquote")
Run Code Online (Sandbox Code Playgroud)


Mic*_*Mic 20

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

请记住,'N' tagName是大写的.

或者,使用更多标签:

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


小智 15

检查此元素是否为 DIV

if (this instanceof HTMLDivElement) {
   alert('this is a div');
}
Run Code Online (Sandbox Code Playgroud)

HTMLUListElementUL相同,
HTMLQuoteElementblockquote


gzt*_*mas 6

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

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


Dir*_*kly 5

if(this.tagName.toLowerCase() == "div"){
    //it's a div
} else {
    //it's not a div
}
Run Code Online (Sandbox Code Playgroud)

编辑:当我写的时候,给出了很多答案,抱歉 doublure