Crel: Fast DOM Creation Utility

4.2.1 · active · verified Sun Apr 19

Crel is a lightweight, minimalist JavaScript utility designed to simplify and accelerate the creation of DOM elements, serving as a more ergonomic alternative to directly using `document.createElement`. It enables developers to construct complex DOM trees with a concise, declarative syntax. The current stable version is 4.2.1, with the project demonstrating an active development and maintenance cadence over its lifetime, having evolved through multiple major versions. Key differentiators include its exceptionally small footprint (under 1KB minified and 500 bytes gzipped), its performance which rivals native `document.createElement` calls, and its avoidance of interference with existing in-DOM event listeners. It also provides a modern Proxy-based API for even cleaner syntax in environments supporting ES6 Proxies, making it suitable for modern evergreen browser applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both the standard `crel` function and its Proxy-based API. It shows how to create and append various DOM elements, including handling attributes and events, illustrating the different ways to attach event listeners based on the API variant used.

import crel from 'crel';

// Standard API usage
const standardButton = crel('button', {
    type: 'button',
    'data-action': 'standard-click' // Direct event attributes like 'onclick' won't work without crel.attrMap['on'] setup
}, 'Click Me (Standard)!');

const infoParagraph = crel('p', 'This element was created using the standard `crel` function syntax.');

const standardDiv = crel('div',
    { 'class': 'standard-example', style: 'padding: 15px; border: 1px solid #ccc; background-color: #f9f9f9;' },
    crel('h2', 'Standard Crel API'),
    infoParagraph,
    standardButton
);

// Attach event listener for the standard button (common alternative if attrMap['on'] isn't configured)
standardButton.addEventListener('click', () => alert('Standard API button clicked (via addEventListener)!'));

// Accessing the Proxy API from the default export
const crelProxy = crel.proxy;

// Proxy API usage
const proxyButton = crelProxy.button({
    type: 'button',
    onclick: () => alert('Proxy API button clicked!') // Proxy API handles 'onclick' directly as an attribute
}, 'Proxy Click Me!');

const proxyInfoParagraph = crelProxy.p('This element was created using the modern Proxy API for cleaner syntax.');

const proxyDiv = crelProxy.div(
    { 'class': 'proxy-example', style: 'margin-top: 20px; padding: 15px; border: 1px solid #cce; background-color: #f0f8ff;' },
    crelProxy.h2('Proxy Crel API'),
    proxyInfoParagraph,
    proxyButton
);

// Append elements to the document body (or a specific container)
document.body.appendChild(standardDiv);
document.body.appendChild(proxyDiv);

console.log('DOM elements created and appended to the document body.');

view raw JSON →