Check if element is a div

Viewed 106293

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

For example:

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

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

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');

Related