Skip to content

Commit 8bed31c

Browse files
author
kai
committed
Add select and selectAll shorthands
1 parent be9ad42 commit 8bed31c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/Component.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,25 @@ 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+
* `Element#querySelector` shorthand
53+
* @param selector A group of selectors
54+
*/
55+
public select<T extends HTMLElement>(selector: string): Component<T> | null {
56+
const element = this.element.querySelector<T>(selector);
57+
if (element == null) return null;
58+
return new Component<T>(element);
59+
}
60+
61+
/**
62+
* `Element#querySelectorAll` shorthand
63+
* @param selector A group of selectors
64+
*/
65+
public selectAll<T extends HTMLElement>(selector: string): Component<T>[] {
66+
const elements = [...this.element.querySelectorAll<T>(selector)];
67+
return elements.map(e => new Component<T>(e));
68+
}
69+
5170
public override on<K extends keyof HTMLElementEventMap>(type: K, listener: (ev: HTMLElementEventMap[K], component: this) => any, options?: boolean | AddEventListenerOptions) {
5271
return super.on(type as any, listener, options);
5372
}

0 commit comments

Comments
 (0)