⚡️ Create complex DOM elements/trees using a functional approach.
This module provides an alternative to JSX or template strings for those who want to build up their DOM trees using plain function composition.
const div h1 h2 button ul li =
Features
- Universal - Works in Node and Browser
- SVG Support - Supports creating SVG Elements
- Functional - Since it's just function composition we can arbitrarily compose them
- Small Only
1.99 kB
minified and gzipped - Interoperability Can be used with diffing libraries like morphdom, nanomorph or anyhting that uses the DOM
Installation
> npm install elementx
Example
const div h1 a = const node = // mount the tree to the DOMdocumentbody console/* * -> * <div class="title"> * <h1>This is a title</h1> * <div class="bg-red"> * <a href="http://github.com">Github</a> * </div> * </div> */
Getting Started
Each HTML tag is exposed as a function when requiring elementx
.
// using destructuringconst div h1 p button =
These functions have the following syntax:
All arguments are optional with at least one argument needing to be present. This kind of function overloading allows you to iterate on your DOM structure really fast and reduce visual noise.
- tagName any valid html tag
- attributes is an object of dom attributes:
{ href: '#header' }
- children can be a string for a text node or an array of nodes
Lifecycle hooks
This module aims to be just the element creation layer. It can be used with any view framework using DOM as their base element abstraction for diffing. Some libraries like this include choo or inu.
SVG
SVG works as expected. Sets the appropriate namespace for both elements and attributes. All SVG tags can only be created with the h
-helper:
const svg = const node = documentbody
Use without helper functions
Sometimes you need to fall back to the traditional createElement(tag, attributes, children)
(aliased to h
), for example svg tags.
const h = const node = console/* * -> * <h1>text</h1> */
Events
All HTML DOM Events can be attached. The casing of the event name doesn't matter (onClick
, onclick
, ONCLICK
etc.)
const node = h documentbody
External tools
- html-to-hyperscript - Web-Service to convert HTML to hyperscript
Tests
> npm test