declarative-element
v2.0.4
Published
Lightweight, simple and reliable boilerplate wrapper for DOM-elements creation
Downloads
32
Maintainers
Keywords
Readme
Declarative Element
Lightweight (1.5KB runtime), simple and reliable boilerplate wrapper for DOM-elements creation
- TypeScript API — nothing is written in pure JS
- Optimized for smaller bundle size — manually + minified by ESBuild
- Covered by tests
- SemVer versioning
- ~~Online demo and query constructor~~ TBA
Installation
npm install declarative-element@latest
Usage
import { getElement } from 'declarative-element';
/** @type {import('declarative-element').Node.WithChildren} */
const input = {
tagName: 'main',
children: [
{
tagName: 'header',
children: [{ tagName: 'h1', innerText: 'HTML Sample' }],
},
{
tagName: 'section',
children: [{ tagName: 'p', innerText: 'Hello, World!' }],
},
],
};
const output = getElement(input);
document.body.appendChild(output);
Samples
{ "tagName": "div", "attributes": { "class": "square" } }
<div class="square"></div>
const element = document.createElement('div');
element.classList.add('square');
{ "tagName": "p", "innerText": "Hello, World!" }
<p>Hello, World!</p>
const element = document.createElement('p');
element.innerHTML = 'Hello, World!';
{
"tagName": "a",
"children": [{ "tagName": "button", "innerText": "Subscribe" }]
}
<a>
<button>Subscribe</button>
</a>
const buttonElement = document.createElement('button');
element.innerHTML = 'Subscribe';
const anchorElement = document.createElement('a');
anchorElement.appendChild(buttonElement);
{
"tagName": "html",
"children": [
{
"tagName": "head",
"children": [{ "tagName": "title", "innerText": "Sample" }]
},
{
"tagName": "body",
"children": [
{ "tagName": "header" },
{ "tagName": "main" },
{ "tagName": "footer" }
]
}
]
}
<html>
<head>
<title>Sample</title>
</head>
<body>
<header></header>
<main></main>
<footer></footer>
</body>
</html>
const titleElement = document.createElement('title');
titleElement.innerHTML = 'Sample';
const headElement = document.createElement('head');
headElement.appendChild(titleElement);
const headerElement = document.createElement('header');
const mainElement = document.createElement('main');
const footerElement = document.createElement('footer');
const bodyElement = document.createElement('body');
bodyElement.appendChild(headerElement);
bodyElement.appendChild(mainElement);
bodyElement.appendChild(footerElement);
const htmlElement = document.createElement('html');
htmlElement.appendChild(headElement);
htmlElement.appendChild(bodyElement);