Skip to content

Commit 312b8b2

Browse files
author
Kai
authored
Add select and selectAll shorthands (#12)
2 parents 09c2805 + 8483533 commit 312b8b2

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/Component.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,31 @@ export class Component<T extends HTMLElement = HTMLElement> extends BaseComponen
4848
return new Component<T>(document.createRange().createContextualFragment(html).children[0] as T);
4949
}
5050

51+
/**
52+
* Get the first component child that matches the specified
53+
* {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors CSS selector}, or group of CSS selectors.
54+
* If no matches are found, null is returned.
55+
*
56+
* @param selectors
57+
* @typeParam T Component element type
58+
*/
59+
public select<T extends HTMLElement = HTMLElement>(selectors: string): Component<T> | null {
60+
const element = this.element.querySelector<T>(selectors);
61+
if (element == null) return null;
62+
return new Component<T>(element);
63+
}
64+
65+
/**
66+
* Get all child components that match the specified
67+
* {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors CSS selector}, or group of CSS selectors.
68+
*
69+
* @param selectors
70+
* @typeParam T Component element type
71+
*/
72+
public selectAll<T extends HTMLElement = HTMLElement>(selectors: string): Component<T>[] {
73+
return [...this.element.querySelectorAll<T>(selectors)].map(e => new Component<T>(e));
74+
}
75+
5176
public override on<K extends keyof HTMLElementEventMap>(type: K, listener: (ev: HTMLElementEventMap[K], component: this) => any, options?: boolean | AddEventListenerOptions) {
5277
return super.on(type as any, listener, options);
5378
}

0 commit comments

Comments
 (0)