Skip to main content

Mini-Hyperscript

This snippet allows you to render HTML in a declarative way. It is especially useful in an environment where you don't want to load a full library like React, for example if you're writing a Tampermonkey script.

Each render completely overwrites the last render.

Usage

<html>
<div id="my-app"></div>
</html>
app.js
const render = mount('#my-app');

/* or:
const render = mount(document.querySelector("#my-app"))
*/

render(
h('main', { style: 'color: red; border: 5px solid green' }, [
h('h1', { textContent: 'Hello World!' }),
h('p', { textContent: 'This is my website.' }),
h('button', { onclick: onClick, textContent: 'Leave' }),
])
);

function onClick() {
render(
h('main', { style: 'color: red; border: 5px solid blue' }, [
h('p', { textContent: 'Goodbye!' }),
])
);
}

Code

mini-hyperscript.js
function h(tagName, props, children = []) {
const element = document.createElement(tagName);
Object.assign(element, props);
for (const child of children) {
element.append(child);
}
return element;
}

function mount(elementOrSelector) {
let element = elementOrSelector;
if (typeof elementOrSelector === 'string') {
element = document.querySelector(elementOrSelector);
}
let root = document.createComment('');
element.append(root);

return (newContent) => {
root.replaceWith(newContent);
root = newContent;
};
}