-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
className.ts
74 lines (69 loc) · 1.79 KB
/
className.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Append CSS classes to an element
* @api private
*/
export const addClass = (
element: HTMLElement | SVGElement,
...classNames: string[]
) => {
for (const className of classNames) {
if (element instanceof SVGElement) {
// svg
const pre = element.getAttribute("class") || "";
if (!pre.match(className)) {
// check if element doesn't already have className
setClass(element, pre, className);
}
} else {
if (element.classList !== undefined) {
// check for modern classList property
element.classList.add(className);
} else if (!element.className.match(className)) {
// check if element doesn't already have className
setClass(element, element.className, className);
}
}
}
};
/**
* Set CSS classes to an element
* @param element element to set class
* @param classNames list of class names
*/
export const setClass = (
element: HTMLElement | SVGElement,
...classNames: string[]
) => {
const className = classNames.filter(Boolean).join(" ");
if (element instanceof SVGElement) {
element.setAttribute("class", className);
} else {
if (element.classList !== undefined) {
element.classList.value = className;
} else {
element.className = className;
}
}
};
/**
* Remove a class from an element
*
* @api private
*/
export const removeClass = (
element: HTMLElement | SVGElement,
classNameRegex: RegExp | string
) => {
if (element instanceof SVGElement) {
const pre = element.getAttribute("class") || "";
element.setAttribute(
"class",
pre.replace(classNameRegex, "").replace(/\s\s+/g, " ").trim()
);
} else {
element.className = element.className
.replace(classNameRegex, "")
.replace(/\s\s+/g, " ")
.trim();
}
};