-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateElementExtended.js
More file actions
85 lines (84 loc) · 2.89 KB
/
Copy pathcreateElementExtended.js
File metadata and controls
85 lines (84 loc) · 2.89 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
/**
* Create a new element, and add some properties to it
*
* @param {string} name The name of the element to create
* @param {object} params The parameters to tweek the new element
* @param {object.<string, string>} params.attributes The propeties of the new element
* @param {object.<string, string>} params.style The style properties of the new element
* @param {string} params.text The textContent of the new element
* @param {HTMLElement[]} params.children The children of the new element
* @param {HTMLElement} params.parent The parent of the new element
* @param {string[]} params.classnames The classnames of the new element
* @param {string} params.id The classnames of the new element
* @param {HTMLElement} params.prevSibling The previous sibling of the new element (to insert after)
* @param {HTMLElement} params.nextSibling The next sibling of the new element (to insert before)
* @param {(element:HTMLElement)=>{}} params.onCreated called when the element is fully created
* @returns {HTMLElement} The created element
*/
const createElementExtended = (name, params) => {
/** @type{HTMLElement} */
const element = document.createElement(name)
if (!params) {
params = {}
}
const { attributes, text, children, parent, prependIn, classnames, id, style, prevSibling, nextSibling, onCreated } = params
if (attributes) {
for (let attributeName in attributes) {
element.setAttribute(attributeName, attributes[attributeName])
}
}
if (style) {
for (let key in style) {
element.style[key] = style[key];
}
}
if (text) {
element.textContent = text;
}
if (children) {
const addChild = (child) => {
if (child) {
if (typeof child === 'string') {
element.appendChild(document.createTextNode(child))
} else if (Array.isArray(child)) {
for (let subChild of child) {
addChild(subChild)
}
} else {
element.appendChild(child)
}
}
}
for (let child of children) {
addChild(child)
}
}
if (parent) {
parent.appendChild(element)
}
if (prependIn) {
prependIn.prepend(element)
}
if (classnames) {
for (let classname of classnames) {
element.classList.add(classname)
}
}
if (id) {
element.id = id
}
if (prevSibling) {
if (prevSibling.parentElement) {
prevSibling.parentElement.insertBefore(element, prevSibling.nextSibling)
} else {
prevSibling.parentElement.appendChild(element)
}
}
if (nextSibling) {
nextSibling.parentElement.insertBefore(element, nextSibling)
}
if (onCreated) {
onCreated(element)
}
return element
}