@medyll/idae-be
v1.97.2
Published
A modern, lightweight, and extensible DOM manipulation library built with TypeScript. Designed for precise element targeting and manipulation using a callback-based approach. Features include advanced DOM traversal, event handling, style management, attri
Maintainers
Readme
@medyll/idae-be
A DOM walk and manipulation library with a callback-based approach for precise element targeting.
Installation
npm install @medyll/idae-beKey Features
- Root object persistence for consistent chaining
- Callback-based element manipulation for precise targeting
- Comprehensive DOM traversal and manipulation
- Event handling with event delegation (
on(event, selector, handler)) - Form serialization and per-field value access (
serializeForm,fieldValue) - Animation helpers on the native Web Animations API (
fade,slideUp,move,scale…) - Style management, and attribute control
- Position measurement (
getDimensions,cumulativeOffset,viewportOffset) and snapping - Timer integration for dynamic operations
- HTTP content loading with failure handling, timeouts and query params
- Standalone utilities:
toArray,toWords,range,createClass,extendObject
Unique Approach
Unlike jQuery and other chained libraries, @medyll/idae-be always returns the root object. This approach allows for consistent chaining while using callbacks to manipulate targeted elements. This design provides more control and clarity in complex DOM operations.
Basic Usage
Example 1: DOM Manipulation with Callbacks
import { be, toBe } from '@medyll/idae-be';
// Select the container element
be('#container')
.append(toBe('<div>New content</div>'), ({ be }) => {
be.addClass('highlight')
.on('click', () => console.log('Clicked!'))
.append(toBe('<span>Nested content</span>'), ({ be }) => {
be.addClass('nested').on('mouseover', () => console.log('Hovered!'));
});
})
.prepend(toBe('<h1>Title</h1>'), ({ be }) => {
be.addClass('title').children(({ be }) => {
be.setStyle({ color: 'blue' });
});
});Example 2: Event Handling and Traversal
import { be } from '@medyll/idae-be';
// Add a click event to all buttons inside the container
be('#container button').on('click', ({ target }) => {
be(target)
.toggleClass('active')
.siblings(({ be }) => {
be.removeClass('active').on('mouseover', () => console.log('Sibling hovered!'));
});
});
// Fire a custom event and handle it
be('#container').fire('customEvent', { detailKey: 'detailValue' }, ({ be }) => {
be.children(({ be }) => {
be.addClass('custom-event-handled');
});
});Example 3: Styling and Attributes
import { be } from '@medyll/idae-be';
// Select an element and update its styles and attributes
be('#element')
.setStyle({ backgroundColor: 'yellow', fontSize: '16px' }, ({ be }) => {
be.setAttr('data-role', 'admin').children(({ be }) => {
be.setStyle({ color: 'red' }).setAttr('data-child', 'true');
});
})
.addClass('styled-element', ({ be }) => {
be.siblings(({ be }) => {
be.setStyle({ opacity: '0.5' });
});
});unwrap(callback?: HandlerCallBackFn): Be
Removes the parent element of the selected element(s), keeping the selected element(s) in the DOM.
Example:
// HTML: <div id="wrapper"><span id="child">Content</span></div>
be('#child').unwrap();
// Result: <span id="child">Content</span>
---
### Example 4: Timers
```javascript
import { be } from '@medyll/idae-be';
// Set a timeout to execute a callback after 100ms
be('#test').timeout(100, ({ be }) => {
be.setStyle({ backgroundColor: 'yellow' }).append('<span>Timeout executed</span>');
});
// Set an interval to execute a callback every 400ms
const intervalInstance = be('#test').interval(400, ({ be }) => {
be.toggleClass('highlight');
});
// Clear the interval after 600ms
setTimeout(() => {
intervalInstance.clearInterval();
}, 600);Example 5: Walk
import { be } from '@medyll/idae-be';
// Traverse up the DOM tree to find the parent element
be('#child').up('#parent', ({ be: parent }) => {
parent.addClass('highlight')
.children(({ be: child }) => {
child.setStyle({ color: 'blue' });
});
});
// Find all siblings of an element and add a class
be('#target').siblings(({ be: siblings }) => {
siblings.addClass('sibling-class').children(({ be }) => {
be.setStyle({ fontWeight: 'bold' });
});
});
// Find the closest ancestor matching a selector
be('#child').closest('.ancestor', ({ be: closest }) => {
closest.setStyle({ border: '2px solid red' }).children(({ be }) => {
be.addClass('ancestor-child');
});
});Example 6: HTTP Content Loading and Insertion
import { be } from '@medyll/idae-be';
// Load content from a URL and update the element
be('#test').updateHttp('/content.html', ({ be }) => {
console.log('Content loaded:', be.html);
});
// Load content and insert it at a specific position
be('#test').insertHttp('/content.html', 'afterbegin', ({ be }) => {
console.log('Content inserted:', be.html);
});API Reference
Core Methods
be(selector: string | HTMLElement | HTMLElement[]): Be
Create a new Be instance.
Example:
const instance = be('#test');toBe(str: string | HTMLElement, options?: { tag?: string }): Be
Convert a string or HTMLElement to a Be instance.
Example:
const newElement = toBe('<div>Content</div>');createBe(tagOrHtml: string, options?: Object): Be
Create a new Be element.
Example:
const newElement = createBe('div', { className: 'my-class' });HTTP Methods
updateHttp(url: string, options?: HttpRequestOptions, callback?: HandlerCallBackFn): Promise<Be>
Loads content from a URL and updates the element's content. Options: method, data, headers, params (query string), timeout (aborts after N ms), onFailure(response, error?) — called instead of the content callback on non-ok responses or network errors; without it, failures throw and error bodies are never injected.
Example:
be('#test').updateHttp('/content.html', {
params: { section: 'news' },
timeout: 5000,
onFailure: (response) => console.error('Load failed', response?.status)
}, ({ be }) => {
console.log(be.html);
});insertHttp(url: string, mode?: 'afterbegin' | 'afterend' | 'beforebegin' | 'beforeend', options?: { params?, timeout?, onFailure? }, callback?: HandlerCallBackFn): Promise<Be>
Loads content from a URL and inserts it into the element at a specified position.
Example:
be('#test').insertHttp('/content.html', 'afterbegin', ({ be }) => {
console.log(be.html);
});Timers
timeout(delay: number, callback: HandlerCallBackFn): Be
Set a timeout for an element.
Example:
be('#test').timeout(1000, () => console.log('Timeout executed'));interval(delay: number, callback: HandlerCallBackFn): Be
Set an interval for an element.
Example:
be('#test').interval(500, () => console.log('Interval executed'));clearTimeout(): Be
Clear a timeout.
Example:
const timeoutInstance = be('#test').timeout(1000, () => console.log('Timeout executed'));
timeoutInstance.clearTimeout();clearInterval(): Be
Clear an interval.
Example:
const intervalInstance = be('#test').interval(500, () => console.log('Interval executed'));
intervalInstance.clearInterval();Traversal
up(selector?: string, callback?: HandlerCallBackFn): Be
Traverse up the DOM tree.
Example:
be('#child').up();next(selector?: string, callback?: HandlerCallBackFn): Be
Traverse to the next sibling.
Example:
be('#sibling1').next();previous(selector?: string, callback?: HandlerCallBackFn): Be
Traverse to the previous sibling.
Example:
be('#sibling2').previous();siblings(selector?: string, callback?: HandlerCallBackFn): Be
Find all sibling elements.
Example:
be('#child').siblings();children(selector?: string, callback?: HandlerCallBackFn): Be
Find all child elements.
Example:
be('#parent').children();closest(selector: string, callback?: HandlerCallBackFn): Be
Find the closest ancestor matching a selector.
Example:
be('#child').closest('#ancestor');Styling
setStyle(styles: Record<string, string>): Be
Set CSS styles for an element.
Example:
be('#test').setStyle({ color: 'red', fontSize: '16px' });getStyle(property: string): string | null
Get the value of a CSS property.
Example:
const color = be('#test').getStyle('color');
console.log(color); // Output: "red"unsetStyle(property: string): Be
Remove a CSS property from an element.
Example:
be('#test').unsetStyle('color');Events
on(eventName: string, handler: EventListener): Be
Add an event listener to an element.
Example:
be('#test').on('click', () => console.log('Clicked!'));on(eventName: string, selector: string, handler: EventListener): Be
Delegated listener: binds once on the element, fires only when the actual event target matches a descendant fitting selector. The handler runs with this set to the matched descendant — works for elements added after binding.
Example:
be('#list').on('click', 'li.item', function () {
be(this).toggleClass('selected');
});off(eventName: string, handler: EventListener): Be
Remove an event listener from an element. For delegated listeners, use off(eventName, selector, handler) with the same triple used at binding time.
Example:
be('#test').off('click', handler);
be('#list').off('click', 'li.item', handler);fire(eventName: string, detail?: any): Be
Dispatch a custom event.
Example:
be('#test').fire('customEvent', { key: 'value' });Forms
serializeForm(options?: { asJSON?: boolean }): string | Record<string, unknown>
Serialize a form to a query string (default) or a plain object (asJSON). Disabled, nameless, unchecked and button/file fields are skipped; multi-selects produce repeated entries or arrays.
Example:
be('#myForm').serializeForm(); // "name=john&tags=a&tags=b"
be('#myForm').serializeForm({ asJSON: true }); // { name: 'john', tags: ['a', 'b'] }fieldValue(): string | string[] | boolean
Get a single field's value — checkbox/radio → checked state, <select multiple> → array of values, anything else → .value.
getFormElements(): HTMLElement[]
Get the form's elements (Array.from(form.elements)).
Effects
Animation helpers on the native Web Animations API — no dependency. Each takes { duration?, easing?, delay? } and an optional callback fired on finish; when el.animate is unavailable, the final state applies synchronously.
fade(options?, callback?): Be / appear(options?, callback?): Be
Fade out (then display: none) / fade in.
slideUp(options?, callback?): Be / slideDown(options?, callback?): Be
Collapse / expand vertically.
move({ x, y, ...options }, callback?): Be
Translate by an offset, left applied.
scale({ from, to, ...options }, callback?): Be
Scale between two factors, left applied.
Example:
be('#toast').appear({ duration: 200 });
be('#panel').slideUp({ duration: 300 }, () => console.log('collapsed'));Position measurement
getDimensions(callback): Be
{ width, height } via the callback fragment — display: none elements are temporarily made measurable, then restored.
cumulativeOffset(callback): Be
{ left, top } relative to the document (accounts for scroll).
viewportOffset(callback): Be
{ left, top } relative to the viewport.
Example:
be('#box').getDimensions(({ fragment }) => console.log(fragment)); // { width: 120, height: 40 }Utilities
Standalone exports (plain functions, not handlers):
import { toArray, toWords, range, createClass, extendObject } from '@medyll/idae-be';
toArray(document.querySelectorAll('div')); // HTMLElement[]
toWords(' alpha beta '); // ['alpha', 'beta']
range(1, 4); // [1, 2, 3, 4]
createClass({ initialize(name) { this.name = name; } }); // runtime class builder
extendObject({ a: 1 }, { b: 2 }); // { a: 1, b: 2 }Architecture
flowchart LR
Target[Selector / Element] --> Be[be()]
Be --> Chain[Chained Operations]
subgraph Operations [DOM Manipulation]
Chain --> Attr[Attributes / Classes]
Chain --> Style[Styles]
Chain --> Events[Event Listeners]
Chain --> Content[Append / Prepend]
end
Chain -- returns --> BeLicense
This project is licensed under the MIT License.
Author: Lebrun Meddy (@medyll)
