|
1 | 1 | // Normally we'd capitalize `ID`, but `Id` matches DOM API function names. |
2 | 2 | export async function firstElementWithId(id: string): Promise<Element> { |
3 | | - const { promise, resolve, reject: _ } = Promise.withResolvers<Element>(); |
4 | | - const currentElem = document.getElementById(id); |
5 | | - if (currentElem) { |
6 | | - resolve(currentElem); |
7 | | - } |
8 | | - const observer = new MutationObserver((mutations: MutationRecord[]) => { |
9 | | - for (const mutation of mutations) { |
10 | | - if ( |
11 | | - mutation.attributeName === "id" && |
12 | | - mutation.target instanceof Element && |
13 | | - mutation.target.getAttribute("id") === id |
14 | | - ) { |
15 | | - resolve(mutation.target); |
16 | | - observer.disconnect(); |
| 3 | + return new Promise((resolve, reject) => { |
| 4 | + try { |
| 5 | + const currentElem = document.getElementById(id); |
| 6 | + if (currentElem) { |
| 7 | + resolve(currentElem); |
17 | 8 | } |
18 | | - } |
19 | | - }); |
| 9 | + const observer = new MutationObserver((mutations: MutationRecord[]) => { |
| 10 | + for (const mutation of mutations) { |
| 11 | + if ( |
| 12 | + mutation.attributeName === "id" && |
| 13 | + mutation.target instanceof Element && |
| 14 | + mutation.target.getAttribute("id") === id |
| 15 | + ) { |
| 16 | + resolve(mutation.target); |
| 17 | + observer.disconnect(); |
| 18 | + } |
| 19 | + } |
| 20 | + }); |
20 | 21 |
|
21 | | - observer.observe(document.body, { |
22 | | - attributeFilter: ["id"], |
23 | | - subtree: true, |
| 22 | + observer.observe(document.body, { |
| 23 | + attributeFilter: ["id"], |
| 24 | + subtree: true, |
| 25 | + }); |
| 26 | + } catch (e) { |
| 27 | + reject(e); |
| 28 | + } |
24 | 29 | }); |
25 | | - return promise; |
26 | 30 | } |
0 commit comments