Skip to content

Instantly share code, notes, and snippets.

@mauroc8
Last active October 17, 2022 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauroc8/dd6550ec75ff93d6517e30ee44218fde to your computer and use it in GitHub Desktop.
Save mauroc8/dd6550ec75ff93d6517e30ee44218fde to your computer and use it in GitHub Desktop.
/** A helper function to create DOM elements in a declarative way.
Example:
```html
<span class="wrapper">
<span class="icon" tabindex="0">
<img src="..." />
</span>
<span class="info">
Hello, world!
</span>
</span>
```
```ts
el({
tag: 'span',
attrs: { class: 'wrapper' },
children: [
el({
tag: 'span',
attrs: { class: 'icon', tabindex: '0' },
children: [
el({
tag: 'img',
props: { src: imgUrl },
})
]
}),
el({
tag: 'span',
attrs: { class: 'info' },
children: ['Hello, world!']
})
]
})
```
*/
function el(config: {
tag: string,
children?: (HTMLElement | string | null)[],
attrs?: Record<string, string>,
props?: Record<string, unknown>
}): HTMLElement {
const {
tag,
children,
attrs,
props
} = config;
const el = document.createElement(tag)
if (attrs) for (const [ attr, value ] of Object.entries(attrs)) {
el.setAttribute(attr, value)
}
if (props) for (const [ prop, value ] of Object.entries(props)) {
el[prop] = value
}
if (children) for (const child of children) if (child) {
el.appendChild(
typeof child === 'object'
? child
: document.createTextNode(child)
)
}
return el
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment