Skip to content

HTML.JS

Metro UI provides a set of functions to craete HTML elements.

Html.js is a lightweight JavaScript library for creating HTML elements with ease. It provides a simple and intuitive API for building HTML structures programmatically.

The Html namespace contains a set of functions to create HTML elements.

Metro UI already includes the Html library. You can use it without any additional installation, but if you want to use it in your project, you can install it with package manager:

Terminal window
npm install @olton/html

or use CDN:

<script type="module">
import * as Html from "https://esm.run/@olton/html";
</script>

Html.js allows you to create HTML elements using JavaScript functions:

// Create elements
const title = h1("Hello, World!");
const container = div(
{ class: "container" },
h1("Welcome to Html.js"),
p("Create HTML elements with JavaScript")
);
// Render to DOM
render([title, container], document.body);

Html.js is built around three core classes:

The base class for all HTML elements providing common functionality for attributes, classes, and styles.

Extends BaseElement for standard HTML elements that can have children.

Extends BaseElement for self-closing HTML elements (like <img>, <input>, etc.).

Html.js provides way to create HTML elements with fabric functions.

const div1 = div(element || "static content", ..., {...options});

All elements accept an options object with the following properties:

  • class: String or Array of classes
  • style: String or Object of styles
  • data: Object of data attributes
  • aria: Object of aria attributes
  • events: Object of event handlers
  • Any valid HTML attribute for the element
const button1 = button(
{
class: ["btn", "btn-primary"],
style: {
backgroundColor: "#007bff",
color: "white",
padding: "10px 15px"
},
data: {
id: 123,
toggle: "modal"
},
aria: {
label: "Submit form"
},
events: {
onclick: "submitForm()"
},
disabled: true
},
"Submit"
);

To render the created elements to the DOM, use the render function:

render(element, targetElement, options);

Options:

  • clear: Boolean (default: true) - clear target element before rendering
  • where: String (default: “beforeend”) - position to insert content (“beforebegin”, “afterbegin”, “beforeend”, “afterend”)

Example:

render(div("Hello"), document.getElementById("app"), { clear: false });

Html.js provides several methods for working with styles:

Add CSS styles to the document:

addStyle({
".container": {
maxWidth: "1200px",
margin: "0 auto"
},
".btn": {
padding: "10px 15px",
borderRadius: 4
}
});

Or as a string:

addStyle(`
.container {
max-width: 1200px;
margin: 0 auto;
}
.btn {
padding: 10px 15px;
border-radius: 4px;
}
`);

Create a style element with optional media query:

const styleElement = createStyleElement(`
.container { max-width: 800px; }
`, "screen and (max-width: 768px)");

Create a CSSStyleSheet object:

const sheet = createStyleSheet();

Add a CSS rule to a stylesheet:

const sheet = createStyleSheet();
addCssRule(sheet, ".container", "max-width: 1200px; margin: 0 auto;");
const loginForm = form(
{ class: "login-form", action: "/login", method: "post" },
h2("Login"),
div(
{ class: "form-group" },
label({ for: "username" }, "Username:"),
input({
id: "username",
name: "username",
type: "text",
placeholder: "Enter username"
})
),
div(
{ class: "form-group" },
label({ for: "password" }, "Password:"),
input({
id: "password",
name: "password",
type: "password",
placeholder: "Enter password"
})
),
div(
{ class: "form-actions" },
button({ type: "submit" }, "Login")
)
);
render(loginForm, document.getElementById("app"));
const users = [
{ id: 1, name: "John", email: "john@example.com" },
{ id: 2, name: "Jane", email: "jane@example.com" },
{ id: 3, name: "Bob", email: "bob@example.com" }
];
const usersTable = table(
{ class: "users-table" },
thead(
tr(
th("ID"),
th("Name"),
th("Email"),
th("Actions")
)
),
tbody(
users.map(user =>
tr(
td(user.id),
td(user.name),
td(user.email),
td(
button(
{
class: "btn-edit",
events: {
onclick: `editUser(${user.id})`
}
},
"Edit"
),
button(
{
class: "btn-delete",
events: {
onclick: `deleteUser(${user.id})`
}
},
"Delete"
)
)
)
)
)
);
render(usersTable, document.getElementById("table-container"));

Html.js provides methods to extract all HTML element functions to the context and restore them:

// Extract all HTML element functions to global scope
HTML.extract();
// Now you can use them directly
document.body.appendChild(
div(
h1("Title"),
p("Content")
).toElement()
);
// Restore the global scope to its original state
HTML.restore();

You can also extract to a specific context:

const ctx = {};
HTML.extract(ctx);
// Now use HTML elements through ctx
ctx.div(ctx.h1("Hello"));

or

function createDocument(){
HTML.extract(this);
document.body.appendChild(
div(
h1("Title"),
p("Content")
).toElement()
);
}