Dom Helper
// dom Helper
const dom = {
get: function(id) {
return document.getElementById(id)
},
create: function(tagName, classListString, parent, labelString) {
let el = document.createElement(tagName)
el.classList.add(
...classListString
.replace(/(,|\.)/g, ' ')
.trim()
.split(/\s+/)
)
if (parent && parent.nodeType > 0) {
parent.appendChild(el)
}
if (labelString) {
el.textContent = labelString
}
return el
},
div: function() {
return this.create('div', ...arguments)
},
span: function() {
return this.create('span', ...arguments)
},
}
// How to use
const appEl = dom.get('app')
// arguments: classListString, parentEl, label
const box1 = dom.div('box red dotted', appEl)
const box2 = dom.div('.box, .red, .dotted', appEl) // dots and commas, no problem
box2.textContent = 'This is red dotted box'
// example with label
const label = 'Button click Me!'
const button = dom.div('button red', appEl, label)