Lodash isElement: How It Confirms a DOM Node
The Lodash _.isElement utility provides a reliable way
to verify whether a given JavaScript value is a DOM element. This
article breaks down the internal checks and exact properties Lodash
inspects—specifically the nodeType property, the
object-like type status, and prototype validation—to reliably
distinguish real DOM elements from plain objects or other data
types.
Under the hood, Lodash implements _.isElement with the
following logical condition:
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
}To determine whether the input is a valid DOM element, Lodash inspects three primary criteria:
1. Object-Like Structure
(isObjectLike)
Before checking DOM-specific attributes, Lodash verifies that the value is "object-like." This requires two conditions:
- The value must not be
null. - The
typeofoperator must return'object'.
This preliminary step filters out primitives (such as strings,
numbers, and booleans) as well as undefined and functions,
preventing runtime errors when accessing properties in the next
steps.
2. The nodeType
Property
The primary property inspected is nodeType. Lodash
checks that:
value.nodeType === 1In the W3C DOM specification, every DOM node exposes a numeric
nodeType property. A value of 1 corresponds to
Node.ELEMENT_NODE (such as <div>,
<p>, or <span>). This
distinguishes element nodes from other DOM node types, such as text
nodes (nodeType === 3), comment nodes
(nodeType === 8), and document fragments
(nodeType === 11).
3. Exclusion of
Plain Objects (!isPlainObject)
To prevent false positives from mock objects or custom object literals, Lodash verifies that the value is not a plain object:
!isPlainObject(value)A standard object literal like { nodeType: 1 } satisfies
the nodeType === 1 check. By verifying that the object's
prototype does not directly inherit from Object.prototype
(or null), Lodash ensures that only host objects or
instances derived from browser DOM classes (such as
HTMLElement or Element) pass the test.