Skip to content

Instantly share code, notes, and snippets.

@fbacall
Last active March 20, 2019 11:36
Show Gist options
  • Save fbacall/b11cc4c44f396f881c5bba0c764b9c70 to your computer and use it in GitHub Desktop.
Save fbacall/b11cc4c44f396f881c5bba0c764b9c70 to your computer and use it in GitHub Desktop.
Easier DOM element creation
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