Last active
October 17, 2022 15:01
-
-
Save mauroc8/dd6550ec75ff93d6517e30ee44218fde to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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