aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/modify-dom.ts
blob: da0944b090f35cafcd563cb80c2bd92d26021db7 (plain)
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
import { observeDOM } from "@/utils/observe-dom";

type Replacements = {
	[key: string]: string | null
};

export class DOMModifier {
	selector: string;
	attributes: Replacements;
	constructor(selector: string, attributes: Replacements) {
		this.selector = selector;
		this.attributes = attributes;
	}
}

export const modifyDOM = (elements: (DOMModifier | null)[]) => {
	let count = 0;

	observeDOM(() => {
		for (let i = 0; i < elements.length; i++) {
			if (elements[i]) {
				const element = document.querySelector(elements[i]!.selector) as HTMLElement | null;
				if (element) {
					const attributes = elements[i]!.attributes as any;
					if (attributes.innerHTML) {
						element.innerHTML = attributes.innerHTML;
					}
					delete attributes.innerHTML;
					for (const attribute in attributes) {
						if (attributes[attribute] === null) {
							element.removeAttribute(attribute);
						} else {
							element.setAttribute(attribute, attributes[attribute]);
						}
					}
					elements[i] = null;
					count++;
					if (count >= elements.length) {
						return true;
					}
				}
			}
		}

		return false;
	});
};