Skip to content

Commit ece3a48

Browse files
committed
get all custom properties & values for an HTML element
1 parent 16f9641 commit ece3a48

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/apps/weblib/js-api/utils.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
export const canBeAccessed = (stylesheet) => {
2+
try {
3+
stylesheet.cssRules;
4+
return true;
5+
} catch (e) {
6+
return false;
7+
}
8+
};
9+
10+
export const getCSSCustomProps = (pfx = "") =>
11+
[...document.styleSheets].filter(canBeAccessed).reduce(
12+
(finalArr, sheet) =>
13+
finalArr.concat(
14+
[...sheet.cssRules]
15+
.filter((rule) => rule.type === 1)
16+
.reduce((propValArr, rule) => {
17+
const props = [...rule.style]
18+
.filter((propName) => propName.trim().indexOf("--" + pfx) === 0)
19+
.map((propName) => propName.trim());
20+
return [...propValArr, ...props];
21+
}, [])
22+
),
23+
[]
24+
);
25+
26+
export const getCSSCustomPropsForElement = (el, pfx = "") => {
27+
const props = getCSSCustomProps(pfx);
28+
const style = getComputedStyle(el);
29+
return props
30+
.map((prop) => [prop, style.getPropertyValue(prop)])
31+
.filter((pv) => pv[1] !== "");
32+
};

0 commit comments

Comments
 (0)