Skip to content

Instantly share code, notes, and snippets.

@olegpolyakov
Last active July 14, 2022 21:10
Show Gist options
  • Save olegpolyakov/5e3034f4b62fb6b19d9aa57cba17ca6f to your computer and use it in GitHub Desktop.
Save olegpolyakov/5e3034f4b62fb6b19d9aa57cba17ca6f to your computer and use it in GitHub Desktop.
A utility function for creating dom elements similar to `React.createElement`
export function createElement(tag, props, ...children) {
const element = document.createElement(tag);
if (props) {
Object.entries(props).forEach(([key, value]) => {
if (key.startsWith('on') && typeof value === 'function') {
element.addEventListener(key.substring(2), value);
} else if (key.startsWith('data-')) {
element.setAttribute(key, value);
} else {
element[key] = value;
}
});
}
children.forEach(child => {
if (Array.isArray(child)) {
return element.append(...child);
}
if (typeof child === 'string' || typeof child === 'number') {
child = document.createTextNode(child);
}
if (child instanceof Node) {
element.appendChild(child);
}
});
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment