Skip to content

Instantly share code, notes, and snippets.

@foxbunny
Last active November 21, 2019 23:04
Show Gist options
  • Save foxbunny/c38a205587679befa9ae5414c7d95838 to your computer and use it in GitHub Desktop.
Save foxbunny/c38a205587679befa9ae5414c7d95838 to your computer and use it in GitHub Desktop.
JSX helper for creating DOM nodes
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