libsui $Query class to support multiple elements in constructor

This commit is contained in:
Max 2024-10-09 11:26:37 +08:00
parent 776d22a443
commit 3074a8e432
2 changed files with 76 additions and 62 deletions

File diff suppressed because one or more lines are too long

View file

@ -19,19 +19,25 @@ function $Query(selector: string | Element): __Query {
} }
class __Query { class __Query {
selector: string | Element | undefined = ""; selector: string | Element | NodeListOf<Element> | undefined = "";
elements: NodeListOf<Element> | null = null; elements: NodeListOf<Element> | null = null;
element: Element | null = null; element: Element | null = null;
constructor(selector: string | Element) { constructor(selector: string | Element | NodeListOf<Element>) {
if (typeof selector === "string") { if (typeof selector === "string") {
this.selector = selector; this.selector = selector;
this.elements = document.querySelectorAll(selector); this.elements = document.querySelectorAll(selector);
if (this.elements.length > 0) { if (this.elements.length > 0) {
this.element = this.elements[0]; this.element = this.elements[0];
} }
} else if (selector instanceof NodeList) {
this.elements = selector;
if (this.elements.length > 0) {
this.element = this.elements[0];
}
} else { } else {
this.element = selector; this.element = selector;
} }
this.selector = selector; this.selector = selector;
} }
@ -51,6 +57,14 @@ class __Query {
return null; return null;
} }
findAll(selector: string): __Query | null {
const elms = this.element?.querySelectorAll(selector);
if (elms) {
return new __Query(elms);
}
return null;
}
closest(selector: string): __Query | null { closest(selector: string): __Query | null {
const elm = this.element?.closest(selector); const elm = this.element?.closest(selector);
if (elm) { if (elm) {