elements
DOM manipulation for multiple elements with reactive support.
API
function elements<T extends Element = Element>(
selector: string
): ReactiveElements<T>
interface ReactiveElements<T extends Element = Element> {
readonly length: number;
[index: number]: ReactiveElement<T>;
forEach(callback: (element: ReactiveElement<T>, index: number) => void): ReactiveElements<T>;
}
forEach
Iterates over all selected elements with reactive support.
const items = elements('.item');
// Apply operations to each element
items.forEach((element, index) => {
element
.text(`Item ${index + 1}`)
.attr({ 'data-index': index.toString() })
.on('click', () => console.log(`Clicked item ${index}`));
});
Basic Usage
Select multiple elements and apply reactive operations to each one.
import { signal } from '@hellajs/core';
import { elements } from '@hellajs/dom';
const status = signal('loading');
// Apply reactive bindings to all status indicators
const statusElements = elements('.status-indicator');
statusElements.forEach(elem => {
elem.text(() => `Status: ${status()}`)
.attr({ class: () => `indicator ${status()}` });
});
// When status changes, all elements update automatically
status('ready');
Key Concepts
Reactive Integration
Each element in the collection maintains its own reactive bindings:
const items = signal(['Apple', 'Banana', 'Cherry']);
const listElements = elements('.fruit-item');
listElements.forEach((elem, index) => {
elem.text(() => items()[index] || 'Empty');
});
// When items change, corresponding elements update
items(['Orange', 'Grape', 'Mango']);
Error Handling
Gracefully handles missing elements:
// If .nonexistent doesn't exist, returns empty collection
const missing = elements('.nonexistent');
console.log(missing.length); // 0
missing.forEach(elem => elem.text('test')); // Safe, no-op on empty collection
// Check if elements exist
const items = elements('.item');
if (items.length > 0) {
items.forEach(elem => elem.text('Found!'));
}
Performance Considerations
elements()
creates reactive wrappers for each DOM element, enabling chainable methods and automatic cleanup. For performance-critical operations on many elements, consider direct DOM manipulation:
const items = elements('.item');
// Reactive (automatic cleanup, but slightly more overhead)
items.forEach(elem => elem.text(() => computedValue()));
// Direct DOM (faster, but manual cleanup required)
items.forEach(elem => {
if (elem.node) {
elem.node.textContent = staticValue;
}
});