Created
September 19, 2022 10:11
-
-
Save Ivannnnn/d614ad26b66f6c7234a88f7d4ec9e7a7 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
function el(...args) { | |
const argMap = { String: "type", Object: "props", Array: "children" }; | |
args.forEach((arg) => (args[argMap[arg.constructor.name]] = arg)); | |
if (!args.props && !args.children) return document.createTextNode(args.type); | |
const $el = document.createElement(args.type); | |
for (let key in args.props || {}) { | |
$el[key.toLowerCase()] === null | |
? $el.addEventListener(key.substr(2).toLowerCase(), args.props[key]) | |
: $el.setAttribute(key, args.props[key]); | |
} | |
args.children?.forEach((child) => $el.appendChild(el(...child))); | |
return $el; | |
} | |
/* USAGE: | |
function onClick(e) { | |
alert(e) | |
} | |
const div = el('div', {}, [ | |
['h2', {}, [['Counter:']]], | |
['button', { onClick, style: 'color: red;' }, [['alert']]], | |
]) | |
document.body.appendChild(div) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment