Explain Codes LogoExplain Codes Logo

Check if element is a div

javascript
element-checking
instanceof
dom-methods
Anton ShumikhinbyAnton Shumikhin·Jan 7, 2025
TLDR

To quickly confirm if an element is a <div>, simply check if element.tagName is equivalent to 'DIV' as tagName is always in uppercase.

if (element.tagName === 'DIV') { // Bingo! You've hit the div jackpot. }

Level up your element checking

While our quick solution works perfectly for a swift check, let's walk through more comprehensive and adaptable methods for different use cases:

Go prototype-level with instanceof

For a deeper type check, we can always validate the element's prototype:

if (element instanceof HTMLDivElement) { // It's a div... 100% No doubts about it. }

Going this route allows us to be more specific about an element's type, offloading the heavy work to JavaScript's polymorphism mechanism.

Keep it trendy with modern JavaScript

For a comprehensive type check capable of handling complex selectors, we turn to Element.matches():

if (element.matches('div')) { // Yup, it's a match. Swipe right. 👌 }

That's modern JavaScript doing its thing, giving us chained and dynamic element checks.

Combo check: Is it a div, ul, or blockquote?

When you're not quite sure what you're after, match multiple element types:

if (/DIV|UL|BLOCKQUOTE/.test(element.tagName)) { alert(`It's ${element.tagName.toLowerCase()}, baby!`); }

How neat is that? We're checking multiple possible elements in one fell swoop. Efficiency FTW.

Native DOM methods: Kicking jQuery out

Preferring vanilla JavaScript over jQuery might be a new standard. Let's check how we can do things natively:

Query, don't $earch

Ditch the $ from jQuery, the native DOM methods document.querySelector() and document.querySelectorAll() are here to save the day:

const isDiv = document.querySelector(element).tagName === 'DIV';

Code like you mean it

Say goodbye to jQuery's complexity and say hello to native DOM cleanliness and performance:

if (element.matches('div.someClass')) { // You've just found your very specific div. Cheers! }

Where tagName might not cut it

While tagName is your reliable friend for most cases, it might not always be the hero you need:

When SVG or custom elements come into play

instanceof or nodeName could be your alternatives when tagName turns its back on you:

Prototype chains, inheritance and the unknown!

Unrecognized tags get treated as HTMLUnknownElement by the parser. Understanding DOM Inheritance can save your day.