Check if element is a div
To quickly confirm if an element is a <div>
, simply check if element.tagName
is equivalent to 'DIV'
as tagName
is always in uppercase.
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:
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()
:
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:
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:
Code like you mean it
Say goodbye to jQuery's complexity and say hello to native DOM cleanliness and performance:
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.
Was this article helpful?