-
Notifications
You must be signed in to change notification settings - Fork 0
/
vElement.js
43 lines (40 loc) · 1.04 KB
/
vElement.js
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
class vElement {
constructor(tagName, attrs, children) {
this.tagName = tagName;
this.attrs = attrs || {};
this.children = children || [];
}
render() {
const el = document.createElement(this.tagName);
for(let attr in this.attrs) {
if (this.attrs.hasOwnProperty(attr)) {
setAttr(el, attr, this.attrs[attr]);
}
}
if (this.children.length) {
this.children.forEach(child => {
if (child instanceof vElement) {
el.appendChild(child.render());
} else {
el.appendChild(document.createTextNode(child));
}
})
}
return el;
}
}
export default function createElement(tagName, attrs, ...children) {
return new vElement(tagName, attrs, children);
}
function setAttr(el, attr, value) {
const tagName = (el.tagName || '').toLowerCase();
if (attr === 'value') {
if (tagName === 'input' || tagName === 'textarea') {
el.value = value;
} else {
el.setAttribute(attr, value);
}
} else {
el.setAttribute(attr, value);
}
}