select-dom
Lightweight querySelector
/All
wrapper that outputs an Array
Install
npm install select-dom
import {$, $$, lastElement, elementExists} from 'select-dom';
import {$, $optional} from 'select-dom/strict.js';
API
Note: if a falsy value is passed as baseElement
, you'll always get an empty result (bd578b9)
$(selector[, baseElement = document])
Maps to baseElement.querySelector(selector)
, except it returns undefined
if it's not found
$('.foo a[href=bar]');
$('.foo a[href=bar]', baseElement);
$('.non-existent', baseElement);
lastElement(selector[, baseElement = document])
Like $()
, except that it returns the last matching item on the page instead of the first one.
elementExists(selector[, baseElement = document])
Tests the existence of one or more elements matching the selector. It's like $()
, except it returns a boolean
.
elementExists('.foo a[href=bar]');
elementExists('.foo a[href=bar]', baseElement);
$$(selector[, baseElements = document])
Maps to baseElements.querySelectorAll(selector)
plus:
- it always returns an array
baseElements
can be a list of elements to query
$$('.foo');
$$('.foo', baseElement);
$$('.foo', [baseElement1, baseElement2]);
/strict.js
The strict export will throw an error if the element is not found, instead of returning undefined
. This is also reflected in the types, which are non-nullable:
import {$, $optional} from 'select-dom/strict.js';
const must: HTMLAnchorElement = $('.foo a[href=bar]');
const optional: HTMLAnchorElement | undefined = $optional('.foo a[href=bar]');
Related
- delegate-it - DOM event delegation, in <1KB.
- doma - Parse an HTML string into
DocumentFragment
or one Element
, in a few bytes.