Proxy Quick DOM
const spec = {
get(o, key) {
return o[key] != null ?
o[key] : o[key] = (...args) => {
const el = document.createElement(key);
args.forEach(arg => {
if (typeof arg === 'string') {
const span = document.createElement('span');
span.innerHTML = arg;
el.appendChild(span);
} else if (typeof arg === 'object') {
if (arg.tagName != null) {
el.appendChild(arg);
} else {
for (let i in arg) {
el.setAttribute(i, arg[i]);
}
}
}
});
return el;
}
},
set(o, key, v) {
o[key] = v;
}
}
const dom = new Proxy({}, spec);
document.body.appendChild(
dom.div(
dom.button('cool'),
dom.h2('some text', { style: 'font-style: italic' }),
dom.br(),
dom.input({ placeholder: 'zevan' })
)
);
const { div, input, label } = dom;
document.body.appendChild(
div(
label(
'Slider:',
{
for: 'slider',
style: 'padding:1em;display:block'
},
input({ id: 'slider', type: 'range' })
)
)
);
In this snippet a proxy is used that makes all html node tagNames
valid methods. Each method can take strings and HTMLElements
as arguments in any order to create a dom structure. This may look familiar to people who have looked a bit deeper into the inner workings of some of the popular UI libraries of the last decade.