Check if a value is a DOM element in JavaScript
Advanced · 4 min read
Code that works with web pages often receives "something" and needs to know whether that something is a page element, like a div or a button. A tooltip helper might accept either an element or a CSS selector string. A UI library might check its argument before attaching an event listener. You need a reliable "is this an element?" test.
In this tutorial you will write isElement(value). You will see why the obvious instanceof HTMLElement breaks outside the browser, and build a check that works everywhere by looking at two properties every element has. You need to know objects, typeof and &&.
Nodes and nodeType
A web page is a tree of nodes. Elements such as <div> are nodes, but so are the bits of text between tags and the document itself. Every node has a nodeType number that says which kind it is:
1means an element3means a text node9means the document
Every node also has a nodeName, a string. For an element it is the tag name, such as 'DIV'.
Where there is no DOM
The DOM, the page tree and its classes like HTMLElement, only exists in a browser. Node, which runs JavaScript on servers and in build tools, has none of it. Code shared between the two must not assume it is there.
Here is the exercise. Try it yourself first if you like, then read on and we will build it.
18 Is the value a DOM element?
hardCheck whether a value is a DOM element. Write it so it does not break where there is no DOM at all.
Stuck? Three hints, smallest first
- 1.
v instanceof HTMLElementthrows whereHTMLElementis not defined, and fails across iframes. - 2. Duck-typing on
nodeType === 1and a stringnodeNameworks everywhere. - 3. Guard with
typeof HTMLElement !== ‘undefined’before using it.
Step 1: the obvious check, and where it breaks
In a browser, value instanceof HTMLElement works for most elements. Outside one, it crashes:
try {
console.log({} instanceof HTMLElement);
} catch (e) {
console.log(e.constructor.name); // ReferenceError
}
HTMLElement is not defined in Node, so even mentioning it throws a ReferenceError. There is a second problem in the browser: an element from inside an iframe (a page embedded in a page) was made by that iframe's own HTMLElement, so instanceof with the outer one says false.
Step 2: guard the global
typeof is the one operator that is safe on a name that doesn't exist. It returns 'undefined' instead of throwing:
console.log(typeof HTMLElement); // undefined (in Node)
function isElementByInstance(v) {
return typeof HTMLElement !== 'undefined' && v instanceof HTMLElement;
}
console.log(isElementByInstance({})); // false
&& stops as soon as the left side is false, so instanceof never runs where HTMLElement is missing. This guard pattern is worth remembering for any global that might not exist. But the check still can't say true outside a browser, and it still fails across iframes.
Step 3: check the shape instead
Rather than asking "were you made by HTMLElement?", ask "do you look like an element?". This is called duck typing: if it walks like a duck and quacks like a duck, treat it as a duck. An element has nodeType 1 and a string nodeName:
function isElement(v) {
return typeof v === 'object'
&& v !== null
&& v.nodeType === 1
&& typeof v.nodeName === 'string';
}
Read it line by line. typeof v === 'object' rules out strings, numbers and undefined. v !== null is needed because typeof null is also 'object', a long-standing quirk. Then the two element properties.
Step 4: test it without a browser
Since the check only looks at those two properties, plain objects carrying them are fair stand-ins for real nodes:
const fakeElement = { nodeType: 1, nodeName: 'DIV', tagName: 'DIV' };
const fakeTextNode = { nodeType: 3, nodeName: '#text' };
const fakeDocument = { nodeType: 9, nodeName: '#document' };
console.log(isElement(fakeElement)); // true
console.log(isElement(fakeTextNode)); // false
console.log(isElement(fakeDocument)); // false
The text node and the document are nodes, but not elements, so they are refused.
Step 5: try the odd inputs
console.log(isElement(null), isElement(undefined), isElement('<div>'), isElement(1), isElement([])); // false false false false false
console.log(isElement({ nodeType: 1 })); // false
console.log(isElement({ nodeType: 1, nodeName: 1 })); // false
console.log(isElement({ nodeType: 2, nodeName: 'DIV' })); // false
A string that contains HTML is not an element. An object with only nodeType, or with a number for nodeName, is refused. So is a wrong nodeType, even with a good name.
Step 6: in a real page
In a browser, the same function gives true for real elements, including ones from iframes, because it never asks which HTMLElement made them:
// isElement(document.querySelector('h1')) -> true
// isElement(document.body) -> true
The full solution
The panel defines the stand-in nodes, the duck-typed isElement and the guarded instanceof version, and prints the result for each kind of value. Press Run to see them. In a browser, try isElement(document.body) in the console as well.
// ---- the stand-in ----------------------------------------------------------
// The build runs in Node, which has no DOM, so these fakes stand in for real
// elements. They carry the exact properties the check looks at, which is the
// point: the check is duck-typed, so a faithful fake passes and a lookalike
// with the wrong nodeType does not.
const fakeElement = { nodeType: 1, nodeName: 'DIV', tagName: 'DIV' };
const fakeTextNode = { nodeType: 3, nodeName: '#text' };
const fakeDocument = { nodeType: 9, nodeName: '#document' };
// ---- the answer ------------------------------------------------------------
// Duck-typing: nodeType 1 is ELEMENT_NODE, and nodeName must be a string.
// Works in Node, in a browser, and across iframes.
function isElement(v) {
return typeof v === 'object'
&& v !== null
&& v.nodeType === 1
&& typeof v.nodeName === 'string';
}
// instanceof, guarded so it does not throw where the global is missing.
function isElementByInstance(v) {
return typeof HTMLElement !== 'undefined' && v instanceof HTMLElement;
}
const hasDom = typeof HTMLElement !== 'undefined';
// In a browser this is the real thing:
// isElement(document.querySelector('h1')) -> true
console.log('running with a real DOM?', hasDom);
console.log('fake element :', isElement(fakeElement));
console.log('fake text node :', isElement(fakeTextNode), '<- nodeType 3, not an element');
console.log('fake document :', isElement(fakeDocument), '<- nodeType 9');
console.log('plain object :', isElement({}));
console.log('the guarded instanceof check did not throw:', isElementByInstance(fakeElement));
Output
15 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an element-shaped value passes', isElement(fakeElement), true);
test('a text node does not', isElement(fakeTextNode), false);
test('because its nodeType is 3', fakeTextNode.nodeType, 3);
test('the document itself does not', isElement(fakeDocument), false);
test('a plain object does not', isElement({}), false);
test('null does not', isElement(null), false);
test('undefined does not', isElement(undefined), false);
test('a string does not', isElement('<div>'), false);
test('a number does not', isElement(1), false);
test('an array does not', isElement([]), false);
test('nodeType alone is not enough without a nodeName', isElement({ nodeType: 1 }), false);
test('and a numeric nodeName is refused', isElement({ nodeType: 1, nodeName: 1 }), false);
test('a wrong nodeType is refused even with a good nodeName', isElement({ nodeType: 2, nodeName: 'DIV' }), false);
test('the guarded instanceof check never throws', typeof isElementByInstance(fakeElement), 'boolean');
test('and returns false where there is no DOM', hasDom ? true : isElementByInstance(fakeElement) === false, true);
Adapted. There is no DOM in the build, so the assertions run against objects carrying the properties a real element carries. That is fair here precisely because the check is duck-typed: it looks only at nodeType and nodeName, so nothing about a real element is being faked away. Open the built page in a browser and isElement(document.body) returns true.
Duck-typing beats instanceof for this one. v instanceof HTMLElement throws a ReferenceError in Node or a worker, and returns false for an element that came from an iframe, because that iframe has its own HTMLElement constructor. Checking nodeType === 1 works in every one of those cases. The typeof HTMLElement !== 'undefined' guard is the general pattern for touching any global that may not exist.
Common mistakes
- Using
instanceof HTMLElementunguarded. It throws a ReferenceError wherever there is no DOM. - Forgetting
v !== null.typeof nullis'object', and then readingnull.nodeTypethrows a TypeError. - Checking only
nodeType.{ nodeType: 1 }would pass. ChecknodeNametoo.
Try it yourself
- Write
isTextNode(v)using the same pattern withnodeType === 3. - Change
isElementto accept an optional tag name, soisElement(v, 'DIV')also checksnodeName. - In a browser console, compare
isElement(document)withisElement(document.documentElement).