Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Last active April 3, 2025 20:20
Show Gist options
  • Select an option

  • Save henriquegogo/0fb36f804b57c029ba4a7b19280bc040 to your computer and use it in GitHub Desktop.

Select an option

Save henriquegogo/0fb36f804b57c029ba4a7b19280bc040 to your computer and use it in GitHub Desktop.
Create HTML Elements with arguments and nested children
const ElementCreator = new Proxy({}, {
get: (_, tag) => function(...args) {
const el = Object.assign(document.createElement(tag), ...args);
el.append(...args.filter(arg => arg.constructor !== Object));
return el;
}
});
const EventsHandler = (fn, el) => ({
update: (newElement) => el.replaceWith(fn(newElement)),
listen: (ev, fn) => (el.dataset.event = "", el)
.addEventListener(ev, ({detail}) => fn(detail)),
dispatch: (ev, detail) => document.querySelectorAll("[data-event]")
.forEach(el => el.dispatchEvent(new CustomEvent(ev, {detail})))
});
const HelloWorld = (message = 'Hello World!') => {
const { div, h1 } = ElementCreator;
const el =
div({
className: 'hello-world',
onclick: () => dispatch('newdata', 'Bye bye')
},
h1(message));
const { update, listen, dispatch } = EventsHandler(HelloWorld, el);
listen('newdata', newMsg => update(newMsg));
listen('newdata', () => console.log('gotcha!'));
return el;
}
document.body.append(HelloWorld());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment