A lightweight helper class to manage HTML element references with deferred DOM operations.
- Deferred element handling (works even if the element doesn't exist yet)
- Proxy properties for common element attributes
- Event listeners for element availability
- Chainable DOM operations
import Ref from 'html-tag-js/ref';
const myRef = Ref();
myRef.id = 'my-element';
myRef.classList.add('container');
myRef.onref = (element) => {
console.log('Element is ready:', element);
};
// Later in your code when element is created
document.body.append(myRef.el);
// Get the actual HTML element (null until created)
const element = myRef.el;
Method | Description |
---|---|
get() |
Query child elements |
getAll() |
Query all matching child elements |
static isRef(value) |
Check if a value is a reference instance |
const btn = myRef.get('#submit-btn');
const images = myRef.getAll('img');
// Set attribute
myRef.attr('data-custom', 'value');
// Get attribute
const value = myRef.attr('data-custom');
// Listen for element availability
myRef.on('ref', (element) => {
console.log('Element ready:', element);
});
// Remove listener
myRef.off('ref', callback);
Set these even if element doesn't exist yet:
myRef.id = 'main-content';
myRef.className = 'page-wrapper';
myRef.style.color = 'red';
myRef.textContent = 'Loading...';
// Append children
myRef.append(otherElement, anotherElement);
import Ref from 'html-tag-js/ref';
// Create reference
const cardRef = Ref();
// Configure element
cardRef.classList.add('card', 'shadow');
cardRef.style.opacity = '0';
cardRef.innerHTML = '<h2>Loading...</h2>';
// Handle element availability
cardRef.onref = (element) => {
element.classList.add('fade-in');
element.style.opacity = '1';
};
// Add to DOM later
setTimeout(() => {
document.body.append(cardRef.el);
}, 1000);
- All property setters work before the element exists
- Getters return stored values until element is created
onref
event fires when element is first assigned/created- Methods like
get()
/getAll()
only work after element exists
This pattern is particularly useful for:
- Web components
- Dynamic UI creation
- Framework-free reactive programming
- Delayed DOM operations