Skip to content

Instantly share code, notes, and snippets.

@kirjavascript

kirjavascript/h2.js

Last active Sep 21, 2020
Embed
What would you like to do?
let c = Symbol();
h = (tag, attrs = {}, children = [], node = document.createElement(tag)) => {
node[c] = children;
Object.entries(attrs).map(([k, v]) =>
/^on/.test(k)
? node.addEventListener(k.slice(2), v)
: node.setAttribute(k, v),
);
return node;
};
render = (node, tree) => (
[...node.childNodes].map((d) => d.remove()),
(r = (node, items) => (
items.map((el) =>
node.appendChild(el instanceof Object ? r(el, el[c]) : new Text(el)),
),
node
))(node, tree)
);
// demo https://jsfiddle.net/2hsp58kd/
// minified
let e=Symbol();h=(t,n={},d=[],o=document.createElement(t))=>(o[e]=d,Object.entries(n).map(([e,t])=>/^on/.test(e)?o.addEventListener(e.slice(2),t):o.setAttribute(e,t)),o),render=(t,n)=>([...t.childNodes].map(e=>e.remove()),(r=(t,n)=>(n.map(n=>t.appendChild(n instanceof Object?r(n,n[e]):new Text(n))),t))(t,n))
// unsafe version
h = (tag, attrs, children = [], node = document.createElement(tag)) => {
node.$ = children;
for(k in attrs) {
/^on/.test(k)
? node[k] = attrs[k]
: node.setAttribute(k, attrs[k])
}
return node;
};
render = (node, tree) => (
node.innerText=[],
(r = (node, items) => (
items.map((el) =>
node.append(el.$? r(el, el.$) : el),
),
node
))(node, tree)
);
// minified, 195 bytes
h=(e,t,n,r=document.createElement(e))=>{for(k in r.$=n,t)/^on/.test(k)?r[k]=t[k]:r.setAttribute(k,t[k]);return r},r=(e,t)=>(e.innerText=[],(r=(e,t)=>(t?.map(t=>e.append(t.$?r(t,t.$):t)),e))(e,t))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment