This repository has been archived by the owner on Oct 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
59 lines (51 loc) · 1.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* @flow strict */
type Queryable = Document | DocumentFragment | Element
class QueryError extends Error {
framesToPop: number
constructor(message) {
super(message)
this.name = 'QueryError'
this.framesToPop = 1
}
}
export function closest<T: Element>(element: Element, selectors: string, type: Class<T>): T {
const klass = type || HTMLElement
const el = element.closest(selectors)
if (el instanceof klass) {
return el
}
throw new QueryError(`Element not found: <${klass.name}> ${selectors}`)
}
export function query<T: Element>(context: Queryable, selectors: string, type: Class<T>): T {
const klass = type || HTMLElement
const el = context.querySelector(selectors)
if (el instanceof klass) {
return el
}
throw new QueryError(`Element not found: <${klass.name}> ${selectors}`)
}
export function querySelectorAll<T: Element>(context: Queryable, selectors: string, type: Class<T>): Array<T> {
const klass = type || HTMLElement
const els: Array<T> = []
for (const el of context.querySelectorAll(selectors)) {
if (el instanceof klass) {
els.push(el)
}
}
return els
}
export function namedItem<T: HTMLElement>(form: HTMLFormElement, itemName: string, type: Class<T>): T {
const klass = type || HTMLInputElement
const el = form.elements.namedItem(itemName)
if (el instanceof klass) {
return el
}
throw new QueryError(`Element not found by name: <${klass.name}> ${itemName}`)
}
export function getAttribute(element: Element, attributeName: string): string {
const attribute = element.getAttribute(attributeName)
if (attribute != null) {
return attribute
}
throw new QueryError(`Attribute not found on element: ${attributeName}`)
}