Skip to content

Commit 64a8017

Browse files
committed
fix findAncestorByAttribute so that it also checks shadow-doms
1 parent 1804537 commit 64a8017

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed
Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,40 @@
11
/**
22
* Recursively find an ancestor element by attribute name and value. This also checks children of the ancestor.
33
* @func findAncestorByAttributeValue
4-
* @param {HTMLElement} element - Origin element of the search.
4+
* @param {HTMLElement} startNode - Origin node of the search.
55
* @param {string} attributeName - Name of the attribute to search for.
66
* @param {string} attributeValue - Value of the attribute to search for.
77
*/
88
export const findAncestorByAttributeValue = (
9-
element: HTMLElement,
9+
startNode: HTMLElement | ParentNode,
1010
attributeName: string,
1111
attributeValue: string
12-
) => {
13-
while (element !== null && element.parentElement !== null) {
14-
element = element.parentElement;
12+
): HTMLElement | null => {
13+
let currentNode: typeof startNode | null = startNode;
1514

15+
while (currentNode !== null) {
16+
// Check if the current element has the specified attribute
1617
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
1923
const elementContainsAttribute =
20-
element.querySelector(`[${attributeName}="${attributeValue}"]`) !== null;
24+
currentNode.querySelector(`[${attributeName}="${attributeValue}"]`) !==
25+
null;
26+
2127
if (elementHasAttribute) {
22-
return element;
28+
return currentNode as HTMLElement; // Found a matching ancestor
2329
} else if (elementContainsAttribute) {
24-
return element.querySelector(
30+
return currentNode.querySelector(
2531
`[${attributeName}="${attributeValue}"]`
26-
) as HTMLElement;
32+
) as HTMLElement; // Found a matching ancestor
2733
}
34+
35+
// Move up the DOM tree to the parent or parentNode, whichever is available
36+
currentNode = currentNode.parentElement || currentNode.parentNode || null;
2837
}
29-
return null;
38+
39+
return null; // No matching ancestor found
3040
};

0 commit comments

Comments
 (0)