-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomBuilder.js
More file actions
127 lines (110 loc) · 2.41 KB
/
Copy pathDomBuilder.js
File metadata and controls
127 lines (110 loc) · 2.41 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
const SVG_URL = "http://www.w3.org/2000/svg";
const SVG_TAGS = [
"svg",
"g",
"circle",
"ellipse",
"line",
"path",
"polygon",
"polyline",
"rect",
];
class DomBuilder {
constructor(element) {
this.element = element;
}
attr(name, value = "") {
this.element.setAttribute(name, value);
return this;
}
style(styleStr) {
this.element.setAttribute("style", styleStr);
return this;
}
/**
*
* @param {Array<DOM | DOMBuilder>} element
*/
append(...elements) {
elements.forEach(e => {
if (isElement(e)) {
this.element.appendChild(e);
} else if (isPromise(e)) {
e.then(actualElem => this.append(actualElem));
} else {
this.element.appendChild(e.build());
}
})
return this;
}
/**
*
* @param {String || Promise<String>} value
* @returns DOMBuilder
*/
inner(value) {
if (isPromise(value)) {
value.then(v => this.element.innerHTML = v);
} else {
this.element.innerHTML = value;
}
return this;
}
removeChildren() {
while (this.element.firstChild) {
this.element.removeChild(this.element.lastChild);
}
return this;
}
html(value) {
return this.inner(value);
}
event(eventName, lambda) {
this.element.addEventListener(eventName, lambda);
return this;
}
build() {
return this.element;
}
addClass(className) {
if (!className || className === "") return this;
this.element.classList.add(...className.split(" "));
return this;
}
removeClass(className) {
this.element.classList.remove(className);
return this;
}
/**
* @param {String | DOM} elem
*/
static of(elem) {
if (isElement(elem)) {
return new DomBuilder(elem);
}
const isSvg = SVG_TAGS.includes(elem);
const element = isSvg ?
document.createElementNS(SVG_URL, elem) :
document.createElement(elem);
// if (isSvg) element.setAttribute("xmlns", SVG_URL);
return new DomBuilder(element);
}
static ofId(id) {
return new DomBuilder(document.getElementById(id));
}
}
//Returns true if it is a DOM element
function isElement(o) {
return typeof HTMLElement === "object"
? o instanceof HTMLElement //DOM2
: o &&
typeof o === "object" &&
o !== null &&
o.nodeType === 1 &&
typeof o.nodeName === "string";
}
function isPromise(o) {
return o instanceof Promise;
}
export default DomBuilder;