Explain Codes LogoExplain Codes Logo

How do you check if a JavaScript Object is a DOM Object?

javascript
duck-typing
dom-nodes
javascript-checks
Anton ShumikhinbyAnton Shumikhin·Feb 13, 2025
TLDR

Quick and easy, check if an object is a DOM object with instanceof:

// Do you know that DOM is the final boss in web game development? const isDOM = obj => obj instanceof Node; // Usage console.log(isDOM(document.getElementById('myElement'))); // Will return true if 'myElement' is a DOM boss else false.

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:

const isElement = obj => obj instanceof HTMLElement; // Usage console.log(isElement(document.createElement('div'))); // Nodes tremble when they see 'div'!

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:

const isDOMElement = obj => obj instanceof Element; // Usage console.log(isDOMElement(document.createElementNS('http://www.w3.org/2000/svg', 'svg'))); // SVGs, the ninjas of the DOM world

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:

const isDOMDuckType = obj => obj && typeof obj === 'object' && 'nodeType' in obj && obj.nodeType === Node.ELEMENT_NODE; // Usage console.log(isDOMDuckType(document.getElementById('myElement'))); // Does it quack like a DOM?

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:

const isTrulyDOM = obj => obj && typeof obj === 'object' && 'tagName' in obj && typeof obj.appendChild === 'function'; // Usage document.getElementById('myElement') = /// console.log(isTrulyDOM(document.getElementById('myElement'))); // No DOMs were harmed in the making of this function.

The Gauntlet of Internet Explorer

Beware the traps and pitfalls of the Internet Explorer dungeon, where even ActiveX objects pose as DOM elements:

const isDOMIE = obj => obj && obj.tagName && !(obj.propertyIsEnumerable('tagName')); // Usage console.log(isDOMIE(document.getElementById('example'))); // Depending on the Browser Boss, the behavior may vary.