Skip to content

Instantly share code, notes, and snippets.

@kirjavascript

kirjavascript/h.js

Last active May 4, 2020
Embed
What would you like to do?
function h(tag, attrs = {}, children = []) {
const node = document.createElement(tag);
node.__children = children;
Object.entries(attrs).forEach(([k, v]) => {
/^on/.test(k)
? node.addEventListener(k.slice(2), v)
: node.setAttribute(k, v);
});
return node;
}
function render(node, tree) {
while(node.firstChild) node.removeChild(node.lastChild);
(function recurse(node, items) {
items.forEach((el) => {
node.appendChild(typeof el !== 'object'
? new Text(el) : recurse(el, el.__children))
});
return node;
})(node, tree);
}
// userland
let value = 23;
render(document.body.appendChild(h('div')), [
h('input', {
type: 'range',
value,
oninput: (e) => {
value = e.target.value;
update();
}}),
]);
const data = document.body.appendChild(h('div'));
function update() {
render(data, [
value
]);
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment