Check if element is a div

前端 未结 11 1334
南方客
南方客 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:20
    if(this.tagName.toLowerCase() == "div"){
        //it's a div
    } else {
        //it's not a div
    }
    

    edit: while I was writing, a lot of answers were given, sorry for doublure

    0 讨论(0)
  • 2021-02-02 05:20
    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 */
    
    0 讨论(0)
  • 2021-02-02 05:24

    Going through jQuery you can use $(this).is('div'):

    Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

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

    Solutions without jQuery are already posted, so I'll post solution using jQuery

    $(this).is("div,ul,blockquote")
    
    0 讨论(0)
  • 2021-02-02 05:25

    Without jQuery you can say this.tagName === 'DIV'

    Keep in mind that the 'N' in tagName is uppercase.

    Or, with more tags:

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

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

    I'm enhancing the answer of Andreq Frenkel, just wanted to add some and it became too lengthy so gone here...

    Thinking about CustomElements extending the existing ones and still being able to check if an element is, say, input, makes me think that instanceof is the best solution for this problem.

    One should be aware though, that instanceof uses referential equality, so HTMLDivElement of a parent window will not be the same as the one of its iframe (or shadow DOM's etc).

    To handle that case, one should use checked element's own window's classes, something like:

    element instanceof element.ownerDocument.defaultView.HTMLDivElement

    0 讨论(0)
提交回复
热议问题