Simple Hyperscript implementation
Hyperscript is a library that defines an API to create HTML elements using function calls. The same API is also used in other libraries like vue and preact.
Here is a very simple implementation of (a subset of) Hyperscript, to more easily create HTML elements.
export class HtmlString {
data: string;
constructor(source: string) {
this.data = source;
}
}
export function html(src: string) {
return new HtmlString(src);
}
export function h(tagName: string, ...args: any[]) {
const $el = document.createElement(tagName);
for (const arg of args) {
if (Array.isArray(arg) && arg[0] instanceof Node) {
for (const item of arg) {
$el.append(item as Node);
}
} else if (arg instanceof Element) {
$el.append(arg);
} else if (arg instanceof HtmlString) {
$el.innerHTML = arg.data;
} else if (typeof arg === "string") {
$el.textContent = arg;
} else if (typeof arg === "object") {
for (const [key, val] of Object.entries(arg)) {
if (key === "style" && typeof val === "object") {
for (const [key2, val2] of Object.entries(val as object)) {
// @ts-ignore
$el.style[key2] = val2;
}
} else {
$el.setAttribute(key, String(val));
}
}
}
}
return $el;
}
export default h;
And here is a usage example:
const $app = document.getElementById("app")!;
$app.append(h("h1", "Hello, World!"));
$app.append(
h("nia-counter", [
h("output", { "data-ref": "output" }),
h("button", { "data-ref": "increment" }, "Inc"),
]),
);
$app.append(
h("p", [
h("span", "First day of 2026: "),
h("nia-formatted-date", { date: "2026-01-01" }, [
h("span", { "data-ref": "output" }),
]),
]),
);