Skip to content

Commit

Permalink
Add expectElements (strict $$) (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Nov 4, 2024
1 parent e36b29f commit 7aa0642
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
32 changes: 31 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,34 @@ function $$<Selected extends Element>(
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<Selector extends string, Selected extends Element = ParseSelector<Selector, HTMLElement>>(
selectors: Selector | readonly Selector[],
baseElements?: BaseElements
): Selected[];
function expectElements<Selected extends Element = HTMLElement>(
selectors: string | readonly string[],
baseElements?: BaseElements
): Selected[];
function expectElements<Selected extends Element>(
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 = $$<Selected>(selectors, baseElements);
if (elements.length > 0) {
return elements;
}

throw new ElementNotFoundError(`Expected elements not found: ${String(selectors)}`);
}

export {$, $$, lastElement, elementExists, expectElement, expectElements};
6 changes: 5 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion strict.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export {$ as $optional, expectElement as $} from './index.js';
export {
$ as $optional,
$$ as $$optional,
expectElement as $,
expectElements as $$,
} from './index.js';

0 comments on commit 7aa0642

Please sign in to comment.