Skip to content

Instantly share code, notes, and snippets.

@erdesigns-eu
Created November 28, 2023 08:26
Show Gist options
  • Save erdesigns-eu/b54c872e034798b648a260af0fec1a6b to your computer and use it in GitHub Desktop.
Save erdesigns-eu/b54c872e034798b648a260af0fec1a6b to your computer and use it in GitHub Desktop.
JSX DOM
const h = (tag, attrs, ...children) => {
const elm = document.createElement(tag)
for (let key in attrs) {
if (key.slice(0, 2) == 'on') {
const evtName = key.slice(2)
const cb = attrs[key]
if (cb == null) continue // we can use null or undefnied to suppress
elm.addEventListener(evtName, cb)
} else if (['disabled', 'autocomplete', 'selected', 'checked'].indexOf(key) > -1) {
if (attrs[key]) {
elm.setAttribute(key, key)
}
} else {
if (attrs[key] == null) continue // Don't set undefined or null attributes
elm.setAttribute(key, attrs[key])
}
}
if (children.length === 0) {
return elm
}
forEach(child => {
if (child instanceof Node) {
elm.appendChild(child)
} else {
elm.appendChild(document.createTextNode(child))
}
}, flatten(children))
return elm
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment