Last active
July 14, 2022 21:10
-
-
Save olegpolyakov/5e3034f4b62fb6b19d9aa57cba17ca6f to your computer and use it in GitHub Desktop.
A utility function for creating dom elements similar to `React.createElement`
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
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