@devstore/html-js
v1.6.1
Published
DOM manipulation utils
Maintainers
Readme
Abstract
html-js is a low-level DOM manipulation and batching utility. It contains various methods for creating, adding and removing DOM elements, as well as managing events and attributes. It is also possible to use built-in methods for certain selectors.
Links
- Wiki documentation.
- Main Git repository.
Features
- Method chaining pattern
- DOM Element manipulation
- Custom event manipulation
- Property and reflection attributes
- Batching by selector
Implementations
useHtml
useHtml is a hook for ReactJS that helps to access the DOM element.
export const Component: React.FC = () => {
const ref = useHtml(element => { /* DOM manipulations with html-js */ });
return <div ref={ref} />;
};Example
Creating a simple button with a click response. create() will create a button element. append will add other elements (more than one is possible) to the created element. addListeners will create a subscription to the onclick event.
const renderButton() {
const button = append(
create('button', {}, 'primary'),
'Hello!'
);
return addListeners(button, {
click: () => console.log('Hello Clicked!')
});
}This can also be written in one line.
const button = addListeners(
append(
create('button', {}, 'primary'),
'Hello!'
), {
click: () => console.log('Hello Clicked!')
}
);This will produce HTML like this
<button class="primary">Hello!</button> <!-- with onclick listener -->Uses
Basic
To get any element, you can use the get() function. When called with a string starting with #, it uses getElementById(). For other selectors, it uses querySelector(). Returns a single element or undefined.
// By ID
const div = get<HTMLDivElement>('#root');
// By any selector
const first = get<HTMLDivElement>('.item');You can specify a root element as the first argument to search within it.
const div = get<HTMLDivElement>(container, '#root');
const child = get<HTMLDivElement>(container, '.child');The create() function will create the element. This is similar to document.createElement().
const div = create('div');The create function can take more arguments: attributes and style classes.
const div = create('div', { tabindex: 0 }, 'my-class', "then-class");The previous example will generate HTML code like this:
<div tabindex="0" class="my-class then-class"></div>Then we can add something else to the created element using the append() function.
const dest = create('div');
const div = append(dest, 'Text');You can use any nesting and number of arguments.
const div = append(
create('div'),
append(
create('b'),
'Hello'
),
append(
create('em'),
'World!'
);
);Get something like this:
<div><b>Hello</b><em>World!</em></div>There are also many other methods: addClass(), addAttributes(), etc. As well as methods for checking the values of attributes and classes. For example, let's add the tabindex attribute to the created div:
const div = addAttributes(
create('div'),
{ tabindex: 0 }
);Events
The addListeners() function is responsible for subscribing to events. One works similar to addEventListener(). You can subscribe to any events. Even custom ones.
const button = addListeners(
create('button'),
{
click: () => console.log('Clicked!'),
customEvent: () => console.log('Hello!')
}
);You can use the subscribe-unsubscribe pattern.
const unsubscriber = subscribe(get('#root'), { click: () => { ... } });
unsubscriber(); // Call for unsubscribe eventsProperties
You can add properties to elements that will be able to call a callback function if they have changed. This can be done using the addProperty() method.
const div = addProperty(
create('div'),
'message',
() => console.log('message changed!')
);You can also display property values as element attributes. For example, you can display the value of the message property.
const options = {
callback: () => console.log('message changed!'),
reflect: true
}
const div = addProperty(create('div'), 'message', options);If we then do div.message = 'Hello!', the HTML code will look something like this:
<div message="Hello!"></div>Custom Events
You can create and catch custom events associated with changing properties. For example, let's say we have a foo property on a nested element and we want it to catch a DOM event.
const container = addListeners(
create('div'),
{
fooChanged: () => console.log('Foo changed!')
}
);To do this, you can use the addEventProperty() function, which will additionally generate fooChanged event if the property has changed.
const fire = addEventProperty(create('div'), 'foo');Then we will add an element with a property to our container that will listen to the event.
const div = append(container, fire);Ready. All that remains is to change the property.
fire.foo = 'Hello!'Batching
You can apply library functions or custom handlers to many elements that match the selector at once. To do this, you need to use the select() or selectAll() functions. They return a Batch object with methods for chaining and batch operations.
select() returns a single result per selector (first match), while selectAll() returns all matches.
const batcher = select('div');
batcher.batch(addAttributes, 'data-processed', 'true');select can be called with just a selector string (searches from document) or with a root element as the first argument.
// Search from document
const items = select('.item');
// Search from a specific root
const batcher = select(get('#root'), 'div', 'span', 'a');You can also receive values after batching in the form of an array. For example, you can collect all the links on the page.
const batcher = select<HTMLLinkElement>('a');
const hrefs = batcher.batch(element => element.href);Batch objects support chaining: you can call select() or selectAll() to add more elements, or append() to add DOM elements directly.
const batcher = select('div')
.selectAll('span')
.append(get('#dom-element'));
batcher.batch((el) => console.log(el.tagName));The elements property gives direct access to the collected array.
const batcher = select('.item');
batcher.elements.forEach(el => el.style.display = 'none');API Reference
Element Creation
| Function | Signature | Description |
|---|---|---|
| create | create(name, attributes?, ...classes) | Creates an element with attributes and CSS classes. |
| createCustomElement | createCustomElement(name) | Creates a custom element by tag name. |
DOM Manipulation
| Function | Signature | Description |
|---|---|---|
| get | get(id) | get(root, id) | Finds an element by ID (#id → getElementById, otherwise querySelector). |
| append | append(container, ...children) | Appends children to container. Flattens arrays, filters falsy values. |
| removeChildren | removeChildren(container) | Removes all child nodes from a container. |
| getEventPath | getEventPath(event) | Returns the event path (event.path or composedPath()). |
Attributes
| Function | Signature | Description |
|---|---|---|
| getAttribute | getAttribute(el, attr) | getAttribute(el, attr, defaults) | Gets an attribute. Return type depends on defaults: boolean, number, string, or custom parser. |
| setAttribute | setAttribute(el, attr, value?) | Sets an attribute. Falsy values (null, undefined, false) remove it. |
| addAttributes | addAttributes(el, attrs) | Sets multiple attributes at once. |
| removeAttributes | removeAttributes(el, ...attrs) | Removes attributes from an element. |
| hasAttribute | hasAttribute(el, attr, ...values) | Checks if an attribute exists with one of the given values. |
Classes
| Function | Signature | Description |
|---|---|---|
| addClass | addClass(el, ...classes) | Adds CSS classes to an element. |
| removeClass | removeClass(el, ...classes) | Removes CSS classes from an element. |
| toggleClass | toggleClass(el, classes) | Toggles CSS classes via object: { className: boolean }. true adds, false removes. |
Events
| Function | Signature | Description |
|---|---|---|
| addListeners | addListeners(el, events, options?) | Adds event listeners. Each handler receives (event, detail). |
| subscribe | subscribe(el, events, options?) | Subscribes to events and returns an unsubscribe function. |
Properties
| Function | Signature | Description |
|---|---|---|
| addProperty | addProperty(el, name, options) | Adds a tracked property with callback, comparator, reflect, and initial value. |
| addProperties | addProperties(el, props) | Adds multiple properties at once. |
| addEventProperty | addEventProperty(el, name, options?) | Adds a property that dispatches <name>Changed custom event on change. |
| addEventReflectAttributes | addEventReflectAttributes(el, ...attrs) | Reflects <attr>Changed events to DOM attributes. |
Styles
| Function | Signature | Description |
|---|---|---|
| setStyle | setStyle(el, style) | Sets CSS styles. Accepts an object or a string ("color: red; font-size: 16px"). |
Selection & Batching
| Function | Signature | Description |
|---|---|---|
| select | select(el, ...selectors) | select(selector) | Selects first match per selector. Returns a Batch object. |
| selectAll | selectAll(el, ...selectors) | selectAll(selector) | Selects all matches per selector. Returns a Batch object. |
| batch | batch(elements, assembler, ...args) | Applies an assembler to each element and returns results array. |
Batch Object
| Property / Method | Type | Description |
|---|---|---|
| elements | E[] | Array of collected elements. |
| batch(assembler, ...args) | R[] | Runs assembler on each element, returns results. |
| select(selector, ...) | Batch<E> | Selects first match, appends to collection. |
| selectAll(selector, ...) | Batch<E> | Selects all matches, appends to collection. |
| append(elements) | Batch<E> | Adds DOM elements to the collection. |
