Skip to content

Instantly share code, notes, and snippets.

@potch
Created April 30, 2022 20:02
Show Gist options
  • Save potch/aefbd5487d0adffb21419f4707e80aa1 to your computer and use it in GitHub Desktop.
Save potch/aefbd5487d0adffb21419f4707e80aa1 to your computer and use it in GitHub Desktop.
small dom generation code, compatible with htm
const set = (el, o) => {
if (o === null) return
if (typeof o === 'function') {
set(el, o(el))
} else if (o instanceof Array) {
el.append(...o)
} else if (o instanceof Promise) {
o.then(r => set(el, r))
} else if (typeof o === 'object' && !(o instanceof Node)) {
Object.entries(o).forEach(p => el.setAttribute(p[0], p[1]));
} else if (typeof o !== "undefined") {
el.append(o)
} else {
console.warn('could not handle childprop', o)
}
};
const make = (tag, ...children) => {
if (typeof tag === "function") {
return tag(...children)
}
const el = document.createElement(tag);
children.forEach(c => set(el, c));
return el
}
// note a few different ways of applying classes
document.body.append(
make('div',
({ classList }) => classList.add('cool'),
make('h1', { "class": "neato" }, "Hello, World"),
make('ul', [1, 2, 3, 4, 5].map(o => make("li", o))),
)
)
// assuming developit/htm is in the env, the following produces the same output
const html = htm.bind(make)
document.body.append(html`
<div class="cool">
<h1 class="neato">Hello, World</h1>
<ul>${[1, 2, 3, 4, 5].map(o => html`<li>${o}</li>`)}</ul>
</div>
`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment