Repository navigation
Html
The Html module provides low-level utilities for creating, manipulating, and managing DOM elements in Base Framework. While most component development uses higher-level abstractions, Html provides essential utilities for direct DOM operations, attribute handling, and element lifecycle management.
Creates a new element with attributes and optionally adds it to a container.
import { Html } from '@base-framework/base';
// Create element
const div = Html.create('div', { class: 'container' }, document.body);
// Create and prepend
const header = Html.create('h1', { text: 'Title' }, div, true);Parameters:
-
tagName(string): HTML tag name ('div', 'span', 'button', etc.) -
attrs(object): Attributes to set on the element -
container(Element): Parent element to append/prepend to -
prepend(boolean): If true, adds element at beginning (default: false)
Returns: The created element
Creates a text node.
const textNode = Html.createText('Hello World', parentElement);Creates a comment node.
const comment = Html.createComment('Placeholder for dynamic content', parentElement);Creates a document fragment for batch DOM operations.
const fragment = Html.createDocFragment();
Html.append(fragment, element1);
Html.append(fragment, element2);
Html.append(container, fragment); // Add all at onceAdds multiple attributes to an element.
Html.addAttributes(element, {
class: 'button primary',
type: 'button',
disabled: true,
'data-id': '123',
'aria-label': 'Submit form',
click: () => console.log('Clicked!')
});Supported Attributes:
- Standard HTML properties (class, id, type, etc.)
- Data attributes (
data-*) - ARIA attributes (
aria-*) - Event handlers (function values)
- innerHTML (raw HTML)
Adds a single attribute to an element.
// Set property
Html.addAttr(element, 'class', 'active');
// Add event listener
Html.addAttr(element, 'click', () => console.log('Clicked'));Special Handling:
- Functions are automatically registered as event listeners
- Event name prefix "on" is optional and automatically removed
- Uses normalized property names (class → className, etc.)
Adds HTML or text content to an element.
// HTML content (detected automatically)
Html.addHtml(div, '<p>This is <strong>HTML</strong></p>');
// Plain text content
Html.addHtml(div, 'This is plain text');Smart Detection:
- Automatically detects if content contains HTML tags
- Uses
innerHTMLfor HTML - Uses
textContentfor plain text (XSS-safe)
Converts HTML attribute names to JavaScript property names.
import { normalizeAttr } from '@base-framework/base';
normalizeAttr('class'); // 'className'
normalizeAttr('for'); // 'htmlFor'
normalizeAttr('readonly'); // 'readOnly'
normalizeAttr('maxlength'); // 'maxLength'
normalizeAttr('tabindex'); // 'tabIndex'Normalized Attributes:
-
class→className -
text→textContent -
for→htmlFor -
readonly→readOnly -
maxlength→maxLength -
cellspacing→cellSpacing -
rowspan→rowSpan -
colspan→colSpan -
tabindex→tabIndex -
contenteditable→contentEditable
Removes "on" prefix from event names.
import { removeEventPrefix } from '@base-framework/base';
removeEventPrefix('onclick'); // 'click'
removeEventPrefix('onmousedown'); // 'mousedown'
removeEventPrefix('click'); // 'click' (unchanged)Appends a child to a parent element.
const div = document.createElement('div');
const span = document.createElement('span');
Html.append(div, span);Prepends a child to a parent element.
// Add to beginning
Html.prepend(div, firstChild);
// Insert before specific node
Html.prepend(div, newChild, existingChild);Removes an element and cleans up all associated data, bindings, and event listeners.
Html.removeElement(element);What it does:
- Removes all data tracking
- Unbinds all data connections
- Recursively cleans up child elements
- Removes element from DOM
- Handles manual destroy markers
Removes a child element (alias for removeElement).
Html.removeChild(element);Removes all children from a container.
Html.removeAll(container);What it does:
- Cleans up data for all child elements
- Clears innerHTML
- Ensures proper memory cleanup
Removes all data, bindings, and tracking from an element and its children (without removing the element from DOM).
Html.removeElementData(element);Use this when you want to clean up data but keep the element in the DOM.
Moves an element to a new parent.
Html.changeParent(element, newContainer);Clones an element.
// Shallow clone (no children)
const shallowCopy = Html.clone(element);
// Deep clone (with children)
const deepCopy = Html.clone(element, true);Populates a select element with options.
const select = document.createElement('select');
Html.setupSelectOptions(select, [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', value: '2' },
{ label: 'Option 3', value: '3' }
], '2'); // Select option 2 by defaultParameters:
-
selectElement(Element): The select element to populate -
options(Array): Array of option objects withlabelandvalue -
defaultValue(string): Value to select by default
// Create a card component
const card = Html.create('div', { class: 'card' }, container);
const header = Html.create('div', { class: 'card-header' }, card);
Html.addHtml(header, '<h3>Card Title</h3>');
const body = Html.create('div', { class: 'card-body' }, card);
Html.addHtml(body, 'Card content goes here');
const footer = Html.create('div', { class: 'card-footer' }, card);
const button = Html.create('button', {
class: 'btn',
text: 'Action',
click: () => console.log('Button clicked')
}, footer);// Use DocumentFragment for better performance
const fragment = Html.createDocFragment();
for (let i = 0; i < 100; i++)
{
const item = Html.create('div', {
class: 'list-item',
text: `Item ${i}`
}, fragment);
}
// Add all items at once (single reflow)
Html.append(container, fragment);// Html.addHtml automatically detects HTML vs text
const userInput = '<script>alert("XSS")</script>';
// This is safe - will be inserted as text, not HTML
Html.addHtml(div, userInput);
// To explicitly insert HTML (only from trusted sources!)
div.innerHTML = trustedHtmlString;const attrs = {
class: 'button',
type: 'submit',
disabled: isDisabled,
'data-id': userId,
'aria-label': 'Submit form',
click: handleClick
};
Html.addAttributes(button, attrs);// Remove old content
Html.removeAll(container);
// Add new content
if (hasData)
{
const content = Html.create('div', { class: 'content' }, container);
Html.addHtml(content, dataHtml);
}
else
{
const empty = Html.create('div', { class: 'empty-state' }, container);
Html.addHtml(empty, 'No data available');
}Components typically use higher-level APIs, but Html is available for direct DOM manipulation:
class CustomComponent extends Component
{
afterSetup()
{
// Direct DOM access when needed
const wrapper = Html.create('div', {
class: 'custom-wrapper'
}, this.elem);
Html.addAttributes(wrapper, {
'data-component': 'custom',
'aria-live': 'polite'
});
}
}class DynamicList extends Component
{
addItem(data)
{
const item = Html.create('li', {
class: 'list-item',
'data-id': data.id,
text: data.name,
click: () => this.selectItem(data.id)
}, this.elem.querySelector('.list'));
}
}Always use Html.removeElement() instead of element.remove() to ensure proper cleanup:
// ✅ Good - cleans up data and bindings
Html.removeElement(element);
// ❌ Bad - leaves data and bindings in memory
element.remove();Use manual destroy tracking to keep elements in DOM but mark them for manual cleanup:
import { DataTracker } from '@base-framework/base';
// Mark element for manual destroy
DataTracker.set(element, 'manual-destroy', true);
// Html.removeElement will now skip DOM removal
Html.removeElement(element); // Cleans data but keeps elementFor multiple element creation:
const fragment = Html.createDocFragment();
// Add many elements to fragment
Html.append(container, fragment); // Single DOM operation// ✅ Good - single call
Html.addAttributes(element, {
class: 'a',
id: 'b',
type: 'c'
});
// ❌ Avoid - multiple calls
Html.addAttr(element, 'class', 'a');
Html.addAttr(element, 'id', 'b');
Html.addAttr(element, 'type', 'c');// Create template once
const template = Html.create('div', { class: 'template' });
// Clone many times
for (let i = 0; i < 100; i++)
{
const clone = Html.clone(template, true);
Html.append(container, clone);
}// ✅ Preferred - use component system
render()
{
return Div({ class: 'card' }, [
H3('Title'),
P('Content')
]);
}
// ⚠️ Only when necessary - direct Html usage
afterSetup()
{
Html.create('div', {}, this.elem);
}// ✅ Good
Html.removeElement(element);
// ❌ Bad - memory leak
element.remove();// ✅ Good - use normalized names
Html.addAttr(element, 'className', 'active');
// ⚠️ Works but less efficient
Html.addAttr(element, 'class', 'active');// ✅ Safe - automatically handled
Html.addHtml(div, userContent);
// ❌ Dangerous - XSS risk
div.innerHTML = userContent;// Html methods typically return early on invalid input
Html.removeAll(null); // Returns this, no error
Html.clone(null); // Returns false
Html.setupSelectOptions(null, []); // Returns false// ❌ Wrong - event won't be tracked
element.onclick = handler;
// ✅ Correct - event properly tracked
Html.addAttr(element, 'click', handler);// ❌ Wrong - leaves data in memory
element.remove();
// ✅ Correct - cleans everything
Html.removeElement(element);// ❌ Wrong - won't work
element.class = 'active';
// ✅ Correct - normalized
Html.addAttr(element, 'class', 'active');
// or
element.className = 'active';