diff --git a/index.ts b/index.ts index 9f47d46..ceb7248 100644 --- a/index.ts +++ b/index.ts @@ -151,4 +151,34 @@ function $$( return [...elements]; // Convert to array } -export {$, $$, lastElement, elementExists, expectElement}; +/** + * @param selectors One or more CSS selectors separated by commas + * @param [baseElements] The element or list of elements to look inside of + * @return An array of elements found + */ +function expectElements>( + selectors: Selector | readonly Selector[], + baseElements?: BaseElements +): Selected[]; +function expectElements( + selectors: string | readonly string[], + baseElements?: BaseElements +): Selected[]; +function expectElements( + selectors: string | readonly string[], + baseElements?: BaseElements, +): Selected[] { + // Shortcut with specified-but-null baseElements + if (arguments.length === 2 && !baseElements) { + throw new ElementNotFoundError('Expected elements not found because the base is specified but null'); + } + + const elements = $$(selectors, baseElements); + if (elements.length > 0) { + return elements; + } + + throw new ElementNotFoundError(`Expected elements not found: ${String(selectors)}`); +} + +export {$, $$, lastElement, elementExists, expectElement, expectElements}; diff --git a/readme.md b/readme.md index d2c045d..ac28c1f 100644 --- a/readme.md +++ b/readme.md @@ -77,10 +77,14 @@ $$('.foo', [baseElement1, baseElement2]); 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: ```ts -import {$, $optional} from 'select-dom/strict.js'; +import {$, $optional, $$, $$optional} from 'select-dom/strict.js'; const must: HTMLAnchorElement = $('.foo a[href=bar]'); // const optional: HTMLAnchorElement | undefined = $optional('.foo a[href=bar]'); + + +const oneOrMore: HTMLAnchorElement[] = $$('.foo a[href=bar]'); // +const zeroOrMore: HTMLAnchorElement[] = $$optional('.foo a[href=bar]'); ``` ## Related diff --git a/strict.ts b/strict.ts index 638e2f4..a27e50e 100644 --- a/strict.ts +++ b/strict.ts @@ -1 +1,6 @@ -export {$ as $optional, expectElement as $} from './index.js'; +export { + $ as $optional, + $$ as $$optional, + expectElement as $, + expectElements as $$, +} from './index.js';