helem

Create DOM elements in one step.

Usage no npm install needed!

<script type="module">
  import helem from 'https://cdn.skypack.dev/helem';
</script>

README

Helem

Create DOM elements in one step.

Installation

  • npm i helem for webpack/your favorite web-bundler.
  • <script src="https://unpkg.com/helem@0.1.0/web/index.js"> for browser iife library.

Usage

Behaves like document.createElement, but allows you to provide attributes, events, and children on initialization.

const element = helem.el('div', { 
    attr: { 
        innerHTML: '<h1>Hello there</h1>' 
    },
    events: {
        'mouseover': () => element.style.color = 'blue'
    }
}, [
    helem.el('p', [ 'This is Helem.' ])
])

document.body.appendChild(element);

Features

Basic elements

Use helem.el to create an element:

const element = helem.el('div', {
    attr: {
        id: 'example-div'
    }
}, [
    helem.el('h1', ['Hello there']),
    helem.el('button', {
        attr: {
            style: {
                border: 'none',
                padding: '0.5rem'
            },
            innerText: 'Click me'
        },
        events: {
            'click': [
                () => console.log('clicked!'),
                (e) => e.target.after(
                    helem.el('span', {
                        attr: {
                            dataset: {
                                clicked: Date.now()
                            }
                        }
                    }, ['You clicked the button.'])
                )
            ]
        }   
    })
]);

document.body.appendChild(element);

Resuable Element Creator

Use helem to create a creator function with css support:

var create = helem('div', { 
    css: {
        '': {
            padding: '1rem',
        },
        '> h1': {
            fontSize: '1rem',
            color: 'blue'
        }
    }
}, [
    helem('h1', ['I am an HTMLHeadingElement']),
    'I am a Text node.'
])

document.body.appendChild(create())
document.body.appendChild(create())
document.body.appendChild(create())

TypeScript support

Use the type parameter on helem or helem.el to specify the type of element you are creating. This will provide more accurate suggestions for the attr field:

import helem from 'helem';

const div: HTMLDivElement = helem.el<HTMLDivElement>('div', { 
    // ...
})