Check if element is a div

前端 未结 11 1349
南方客
南方客 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: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

提交回复
热议问题