Skip to content
tech_e edited this page Dec 23, 2025 · 1 revision

Html - DOM Manipulation Utilities

Overview

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.

Core Methods

Element Creation

Html.create(tagName, attrs, container, prepend)

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

Text & Comment Nodes

Html.createText(text, container)

Creates a text node.

const textNode = Html.createText('Hello World', parentElement);

Html.createComment(text, container)

Creates a comment node.

const comment = Html.createComment('Placeholder for dynamic content', parentElement);

Html.createDocFragment()

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 once

Attribute Management

Html.addAttributes(element, attrs)

Adds 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)

Html.addAttr(element, attr, value)

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.)

Html.addHtml(element, content)

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 innerHTML for HTML
  • Uses textContent for plain text (XSS-safe)

Attribute Normalization

normalizeAttr(attrName)

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

removeEventPrefix(propName)

Removes "on" prefix from event names.

import { removeEventPrefix } from '@base-framework/base';

removeEventPrefix('onclick');    // 'click'
removeEventPrefix('onmousedown'); // 'mousedown'
removeEventPrefix('click');      // 'click' (unchanged)

DOM Manipulation

Append & Prepend

Html.append(parent, child)

Appends a child to a parent element.

const div = document.createElement('div');
const span = document.createElement('span');
Html.append(div, span);

Html.prepend(parent, child, optionalNode)

Prepends a child to a parent element.

// Add to beginning
Html.prepend(div, firstChild);

// Insert before specific node
Html.prepend(div, newChild, existingChild);

Element Removal

Html.removeElement(element)

Removes an element and cleans up all associated data, bindings, and event listeners.

Html.removeElement(element);

What it does:

  1. Removes all data tracking
  2. Unbinds all data connections
  3. Recursively cleans up child elements
  4. Removes element from DOM
  5. Handles manual destroy markers

Html.removeChild(child)

Removes a child element (alias for removeElement).

Html.removeChild(element);

Html.removeAll(container)

Removes all children from a container.

Html.removeAll(container);

What it does:

  1. Cleans up data for all child elements
  2. Clears innerHTML
  3. Ensures proper memory cleanup

Html.removeElementData(element)

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.

Other Operations

Html.changeParent(child, newParent)

Moves an element to a new parent.

Html.changeParent(element, newContainer);

Html.clone(element, deepCopy)

Clones an element.

// Shallow clone (no children)
const shallowCopy = Html.clone(element);

// Deep clone (with children)
const deepCopy = Html.clone(element, true);

Select Element Utilities

Html.setupSelectOptions(selectElement, options, defaultValue)

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 default

Parameters:

  • selectElement (Element): The select element to populate
  • options (Array): Array of option objects with label and value
  • defaultValue (string): Value to select by default

Common Patterns

Creating Complex Structures

// 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);

Batch DOM Operations

// 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);

Safe HTML Insertion

// 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;

Dynamic Attribute Setting

const attrs = {
    class: 'button',
    type: 'submit',
    disabled: isDisabled,
    'data-id': userId,
    'aria-label': 'Submit form',
    click: handleClick
};

Html.addAttributes(button, attrs);

Conditional Rendering

// 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');
}

Integration with Components

Low-Level DOM Access

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'
        });
    }
}

Manual Element Creation

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'));
    }
}

Memory Management

Proper Cleanup

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();

Manual Destroy Tracking

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 element

Performance Tips

1. Use DocumentFragments

For multiple element creation:

const fragment = Html.createDocFragment();
// Add many elements to fragment
Html.append(container, fragment);  // Single DOM operation

2. Batch Attribute Changes

// ✅ 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');

3. Clone for Templates

// 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);
}

Best Practices

1. Use Higher-Level APIs First

// ✅ 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);
}

2. Always Clean Up

// ✅ Good
Html.removeElement(element);

// ❌ Bad - memory leak
element.remove();

3. Normalize Attributes

// ✅ Good - use normalized names
Html.addAttr(element, 'className', 'active');

// ⚠️ Works but less efficient
Html.addAttr(element, 'class', 'active');

4. Safe Content Insertion

// ✅ Safe - automatically handled
Html.addHtml(div, userContent);

// ❌ Dangerous - XSS risk
div.innerHTML = userContent;

Error Handling

// 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

Common Issues

Event Handlers Not Working

// ❌ Wrong - event won't be tracked
element.onclick = handler;

// ✅ Correct - event properly tracked
Html.addAttr(element, 'click', handler);

Memory Leaks

// ❌ Wrong - leaves data in memory
element.remove();

// ✅ Correct - cleans everything
Html.removeElement(element);

Attribute Names

// ❌ Wrong - won't work
element.class = 'active';

// ✅ Correct - normalized
Html.addAttr(element, 'class', 'active');
// or
element.className = 'active';

Clone this wiki locally