How do you check if a JavaScript Object is a DOM Object?
Quick and easy, check if an object is a DOM object with instanceof
:
Under the hood, we're benefitting from the DOM Node interface, which all DOM objects inherit from, making it a trusty ally for DOM element checks.
More than just DOM: Nodes and Elements
While instanceof Node
may defeat most of the bosses, differentiating between DOM Node types is sometimes necessary. For those extra tough battles, determine if an object is an Element Node:
Preparing for all events: Compatibility and Edge Cases
Not every battle arena is the same. HTMLElement
might desert you in non-browser environments or when facing exotic elements like SVGs. For a more stalwart warrior, call Element
:
This check includes those elusive HTML and SVG elements, and it even brushes shoulders with IE8.
Leveling up Your Checks and Beating the Browser Bosses
Duck-typing: The DOM Trickster's Method
You can be cunning as a rogue with duck-typing — check if an object quacks like a DOM object:
That's some crafty code right there!
To be or not to be (a DOM)
A convincing disguise does not make a DOM. Ensure the object behaves like a DOM:
The Gauntlet of Internet Explorer
Beware the traps and pitfalls of the Internet Explorer dungeon, where even ActiveX objects pose as DOM elements:
Was this article helpful?