|
1 | 1 | /**
|
2 | 2 | * Recursively find an ancestor element by attribute name and value. This also checks children of the ancestor.
|
3 | 3 | * @func findAncestorByAttributeValue
|
4 |
| - * @param {HTMLElement} element - Origin element of the search. |
| 4 | + * @param {HTMLElement} startNode - Origin node of the search. |
5 | 5 | * @param {string} attributeName - Name of the attribute to search for.
|
6 | 6 | * @param {string} attributeValue - Value of the attribute to search for.
|
7 | 7 | */
|
8 | 8 | export const findAncestorByAttributeValue = (
|
9 |
| - element: HTMLElement, |
| 9 | + startNode: HTMLElement | ParentNode, |
10 | 10 | attributeName: string,
|
11 | 11 | attributeValue: string
|
12 |
| -) => { |
13 |
| - while (element !== null && element.parentElement !== null) { |
14 |
| - element = element.parentElement; |
| 12 | +): HTMLElement | null => { |
| 13 | + let currentNode: typeof startNode | null = startNode; |
15 | 14 |
|
| 15 | + while (currentNode !== null) { |
| 16 | + // Check if the current element has the specified attribute |
16 | 17 | const elementHasAttribute =
|
17 |
| - element.hasAttribute(attributeName) && |
18 |
| - element.getAttribute(attributeName) === attributeValue; |
| 18 | + currentNode instanceof HTMLElement && |
| 19 | + currentNode.hasAttribute(attributeName) && |
| 20 | + currentNode.getAttribute(attributeName) === attributeValue; |
| 21 | + |
| 22 | + // Check if the current element contains an element with the specified attribute |
19 | 23 | const elementContainsAttribute =
|
20 |
| - element.querySelector(`[${attributeName}="${attributeValue}"]`) !== null; |
| 24 | + currentNode.querySelector(`[${attributeName}="${attributeValue}"]`) !== |
| 25 | + null; |
| 26 | + |
21 | 27 | if (elementHasAttribute) {
|
22 |
| - return element; |
| 28 | + return currentNode as HTMLElement; // Found a matching ancestor |
23 | 29 | } else if (elementContainsAttribute) {
|
24 |
| - return element.querySelector( |
| 30 | + return currentNode.querySelector( |
25 | 31 | `[${attributeName}="${attributeValue}"]`
|
26 |
| - ) as HTMLElement; |
| 32 | + ) as HTMLElement; // Found a matching ancestor |
27 | 33 | }
|
| 34 | + |
| 35 | + // Move up the DOM tree to the parent or parentNode, whichever is available |
| 36 | + currentNode = currentNode.parentElement || currentNode.parentNode || null; |
28 | 37 | }
|
29 |
| - return null; |
| 38 | + |
| 39 | + return null; // No matching ancestor found |
30 | 40 | };
|
0 commit comments