Skip to content

Commit 2864622

Browse files
committed
add findAncestorByAttributeValue function to utils in uui-base
1 parent de41d3f commit 2864622

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Recursively find an ancestor element by attribute name and value. This also checks children of the ancestor.
3+
* @func findAncestorByAttributeValue
4+
* @param {HTMLElement} element - Origin element of the search.
5+
* @param {string} attributeName - Name of the attribute to search for.
6+
* @param {string} attributeValue - Value of the attribute to search for.
7+
*/
8+
export const findAncestorByAttributeValue = (
9+
element: HTMLElement,
10+
attributeName: string,
11+
attributeValue: string
12+
) => {
13+
while (element !== null && element.parentElement !== null) {
14+
element = element.parentElement;
15+
16+
const elementHasAttribute =
17+
element.hasAttribute(attributeName) &&
18+
element.getAttribute(attributeName) === attributeValue;
19+
const elementContainsAttribute =
20+
element.querySelector(`[${attributeName}="${attributeValue}"]`) !== null;
21+
if (elementHasAttribute) {
22+
return element;
23+
} else if (elementContainsAttribute) {
24+
return element.querySelector(
25+
`[${attributeName}="${attributeValue}"]`
26+
) as HTMLElement;
27+
}
28+
}
29+
return null;
30+
};

0 commit comments

Comments
 (0)