Check if element is a div

前端 未结 11 1335
南方客
南方客 2021-02-02 04:44

How do I check if $(this) is a div, ul or blockquote?

For example:

if ($(this) is a div) {
  alert(\'         


        
相关标签:
11条回答
  • 2021-02-02 05:33

    Try using tagName

    0 讨论(0)
  • 2021-02-02 05:39

    To check if this element is DIV

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

    Same for HTMLUListElement for UL,
    HTMLQuoteElement for blockquote

    0 讨论(0)
  • 2021-02-02 05:44

    Something like this:

    if(this.tagName == 'DIV') {
        alert("It's a div!");
    } else {
        alert("It's not a div! [some other stuff]");
    }
    
    0 讨论(0)
  • 2021-02-02 05:44

    Old question but since none of the answers mentions this, a modern alternative, without jquery, could be just using a CSS selector and Element.matches()

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

    0 讨论(0)
  • 2021-02-02 05:45

    Some of these solutions are going a bit overboard. All you need is tagName from regular old JavaScript. You don't really get any benefit from re-wrapping the whole thing in jQuery again, and especially running some of the more powerful functions in the library to check the tag name. If you want to test it on this page, here's an example.

    $("body > *").each(function() {
      if (this.tagName === "DIV") {
        alert("Yeah, this is a div");
      } else {
        alert("Bummer, this isn't");
      }
    });
    
    0 讨论(0)
提交回复
热议问题