Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active November 6, 2022 09:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/35dd025e927b0c7dbf737a849fb75f8a to your computer and use it in GitHub Desktop.
Save gordonbrander/35dd025e927b0c7dbf737a849fb75f8a to your computer and use it in GitHub Desktop.
Dom from simple VDOM
const dom = ({tag='div', attributes={}, styles={}, classes=[], text=null, children=null}) => {
const el = document.createElement(tag)
el.className = classes.join(' ')
for (let [key, value] of Object.entries(attributes)) {
if (value) {
el.setAttribute(key, value)
}
}
for (let [key, value] of Object.entries(styles)) {
el.style[key] = value
}
if (text) {
el.appendChild(document.createTextNode(text));
}
if (children) {
for (let child of children.map(dom)) {
el.appendChild(child)
}
}
return el
}
const el = dom({
classes: ['a', 'b'],
attributes: {
'id': 'bar'
},
styles: {
background: 'black'
},
children: [
{
tag: 'p',
text: 'hello world'
}
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment