Lodash isElement with Shadow DOM Nodes

Lodash provides the _.isElement utility to determine whether a given value is likely a DOM element. When working with the Shadow DOM, developers often wonder how encapsulated nodes and shadow roots are evaluated. This article outlines the specific node properties required by _.isElement, explains how it evaluates elements inside a shadow tree, and clarifies why a ShadowRoot instance itself is treated differently.

Core Properties Checked by _.isElement

Under the hood, Lodash's _.isElement implementation relies on three strict criteria:

  1. nodeType === 1: The property nodeType must be strictly equal to the number 1, representing an Element (Node.ELEMENT_NODE).
  2. Object Type (isObjectLike): The value must be a non-null object (typeof value === 'object' && value !== null).
  3. Prototype Identity (!isPlainObject): The object must not be a plain JavaScript object literal. It must inherit from a prototype chain typical of DOM nodes (such as Element.prototype or Node.prototype) rather than Object.prototype.

Shadow DOM Elements vs. ShadowRoot

When dealing with modern Web Components and the Shadow DOM, distinction must be made between elements within the shadow tree and the shadow root itself:

Elements Inside a Shadow Tree

Any standard HTML or custom element appended inside a shadow tree meets all mandated properties:

The ShadowRoot Node

A ShadowRoot boundary itself is not an Element; it is a document fragment.

Summary Checklist for Node Compatibility

To ensure any node—whether native, slotted, or mocked in a test environment involving the Shadow DOM—is recognized by _.isElement, it must satisfy: