-
-
Save fbacall/b11cc4c44f396f881c5bba0c764b9c70 to your computer and use it in GitHub Desktop.
Easier DOM element creation
This file contains 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
function t(type, htmlPropsOrFirstChild, ...children) { | |
const element = document.createElement(type); | |
if (htmlPropsOrFirstChild) { | |
if (htmlPropsOrFirstChild.constructor === Object) { | |
Object.assign(element, htmlPropsOrFirstChild); | |
} else { | |
children.unshift(htmlPropsOrFirstChild); | |
} | |
} | |
children.forEach((child) => { | |
element.appendChild((typeof child === 'string') ? document.createTextNode(child) : child); | |
}); | |
return element; | |
} | |
// Example usage | |
const content = | |
t('div', { className: 'wrapper' }, | |
t('div', { className: 'header' }, | |
t('h1', 'Top 3 coolest things') | |
), | |
t('div', { className: 'body' }, | |
'Some content...', | |
t('ul', | |
t('li', 'thing 1'), | |
t('li', 'thing 2'), | |
t('li', 'thing 3') | |
), | |
'By the way, ', | |
t('a', { href: 'http://example.com' }, 'check out my website') | |
), | |
t('div', { className: 'footer' }, | |
'The footer' | |
) | |
); | |
document.body.appendChild(content); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment