select-dom [![][badge-gzip]][link-npm] [![npm downloads][badge-downloads]][link-npm]

May 1, 2026 ยท View on GitHub

Lightweight querySelector/All/closest wrapper that returns an array and optionally throws if elements are not found

Install

npm install select-dom
import {
	$,
	$$,
	lastElement,
	elementExists,
	assertElementExists,
	$optional,
	$$optional,
	lastElementOptional,
	$closest,
	$closestOptional,
} from 'select-dom';

API

Note: if a falsy value is passed as baseElement, $, $$, lastElement throw ElementNotFoundError, while $optional, $$optional, lastElementOptional return undefined/[] (bd578b9)

$

$optional

$ maps to baseElement.querySelector(selector), except it throws ElementNotFoundError if no element is found. $optional returns undefined instead of throwing.

$('.foo a[href=bar]');
// => <Element>

$('.non-existent');
// throws ElementNotFoundError

$optional('.non-existent');
// => undefined

$$

$$optional

$$ maps to baseElements.querySelectorAll(selector) and always returns an array. baseElements can also be an array of elements to search within. Throws ElementNotFoundError if no elements are found. $$optional returns [] instead of throwing.

$$('.foo');
// => [<Element>, <Element>, <Element>]

$$('.foo', baseElement);
// => [<Element>, <Element>, <Element>]

$$('.foo', [baseElement1, baseElement2]);
// => [<Element>, <Element>, <Element>]

$$('.non-existent');
// throws ElementNotFoundError

$$optional('.non-existent');
// => []

lastElement

lastElementOptional

Like $/$optional, except they return the last matching element instead of the first.

lastElement('.foo');
// => <Element>

lastElement('.non-existent');
// throws ElementNotFoundError

lastElementOptional('.non-existent');
// => undefined

$closest

$closestOptional

Like element.closest(selector), except baseElement can be any Node including text nodes. $closest throws ElementNotFoundError if not found; $closestOptional returns undefined.

$closest('button', event.target);
// => <button>

$closest('button', button.firstChild); // text nodes are supported
// => <button>

$closest('.non-existent', element);
// throws ElementNotFoundError

$closestOptional('.non-existent', element);
// => undefined

elementExists

Tests the existence of one or more elements. Like $optional(), but returns a boolean.

elementExists('.foo a[href=bar]');
// => true/false

assertElementExists

Like elementExists(), but throws ElementNotFoundError instead of returning false.

assertElementExists('.foo a[href=bar]');
// => void (if element exists)
// => throws ElementNotFoundError (if element doesn't exist)

countElements

Counts the number of elements found. Shortcut for $$optional(selector).length.

countElements('a');
// => 3
  • delegate-it - DOM event delegation, in <1KB.
  • doma - Parse an HTML string into DocumentFragment or one Element, in a few bytes.