パッケージの詳細

@giovanni1707/dom-helpers

giovanni1707668MIT2.3.1

A powerful, high-performance vanilla JavaScript DOM manipulation library with intelligent caching, automatic enhancement, declarative APIs, and bulk element creation

dom, dom-manipulation, vanilla-javascript, dom-helpers

readme

Sponsor

DOM Helpers

npm version License: MIT

A powerful, high-performance vanilla JavaScript DOM manipulation library that transforms how you interact with the DOM. Built with intelligent caching, automatic enhancement, and a declarative API that makes complex DOM operations simple and intuitive.

✨ Features

  • 🎯 Intelligent Element Access: Smart caching system for lightning-fast element retrieval
  • 🔄 Universal Update Method: Declarative .update() method for all DOM elements and collections
  • Bulk Element Creation: Create multiple elements in one call with createElement.bulk()
  • 📦 Multiple Access Patterns: Access elements by ID, class, tag name, or CSS selectors
  • 🚀 Performance Optimized: Built-in fine-grained updates and automatic cleanup
  • 🛡️ Error Resilient: Comprehensive error handling with graceful fallbacks
  • 🔧 Zero Dependencies: Pure vanilla JavaScript with no external dependencies
  • 📱 Browser Compatible: Works across all modern browsers (IE 9+)
  • 🎨 Modular Architecture: Use core library or include specialized modules

📦 Installation

Option 1: NPM (Recommended for projects)

npm install @giovanni1707/dom-helpers

Option 2: CDN (No installation required!)

Include directly in your HTML using jsDelivr CDN:

<!-- Core library (minified) -->
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers.min.js"></script>

<!-- Or use the combined version with all modules -->
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-combined.min.js"></script>

<!-- Individual modules -->
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-storage.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-form.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-animation.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-components.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-reactive.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers-async.min.js"></script>

Pro Tip: For production, always use a specific version number. For latest version, use @latest:

<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@latest/dist/dom-helpers.min.js"></script>

Option 3: GitHub CDN

Alternatively, load directly from GitHub:

<script src="https://cdn.jsdelivr.net/gh/giovanni1707/dom-helpers-js@main/dist/dom-helpers.min.js"></script>

🚀 Quick Start

DOM Helpers gives you the power of declarative updates with the simplicity of vanilla JS. No frameworks, no heavy abstractions—just a clean, unified API that saves time, reduces boilerplate, and keeps full control of the DOM in your hands.”

Basic Usage with dom-helpers library

Using CDN (Quick & Easy)

<!DOCTYPE html>
<html>
<head>
    <title>DOM Helpers Demo</title>
</head>
<body>
    <button id="myButton" class="btn">Click Me</button>
    <div class="container">
        <p class="message">Hello World</p>
    </div>

    <!-- Load from jsDelivr CDN -->
    <script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers.min.js"></script>
    <script>
        // Library is ready to use - no imports needed!
        Elements.myButton.update({
            textContent: 'Enhanced Button!',
            style: { 
                backgroundColor: '#007bff',
                color: 'white',
                padding: '10px 20px'
            },
            addEventListener: {
                click: () => alert('Button clicked!')
            }
        });

        Collections.ClassName.message.update({
            style: { color: 'blue', fontWeight: 'bold' }
        });

        Selector.query('.container').update({
            style: { border: '2px solid #ccc', padding: '20px' }
        });
    </script>
</body>
</html>

Using NPM Installation

<!DOCTYPE html>
<html>
<head>
    <title>DOM Helpers Demo</title>
</head>
<body>
    <button id="myButton" class="btn">Click Me</button>
    <div class="container">
        <p class="message">Hello World</p>
    </div>

    <script src="node_modules/@giovanni1707/dom-helpers/src/dom-helpers.js"></script>
    <script>
        // Access element by ID - automatically enhanced with .update() method
        Elements.myButton.update({
            textContent: 'Enhanced Button!',
            style: { 
                backgroundColor: '#007bff',
                color: 'white',
                padding: '10px 20px'
            },
            addEventListener: {
                click: () => alert('Button clicked!')
            }
        });

        // Access elements by class name
        Collections.ClassName.message.update({
            style: { color: 'blue', fontWeight: 'bold' }
        });

        // Use CSS selectors
        Selector.query('.container').update({
            style: { border: '2px solid #ccc', padding: '20px' }
        });
    </script>
</body>
</html>

Without dom-helpers library

<!DOCTYPE html>
<html>
<head>
    <title>DOM Helpers Demo</title>
</head>
<body>
    <button id="myButton" class="btn">Click Me</button>
    <div class="container">
        <p class="message">Hello World</p>
    </div>

    <script>
       // Access element by ID
const myButton = document.getElementById('myButton');
myButton.textContent = 'Enhanced Button!';
myButton.style.backgroundColor = '#007bff';
myButton.style.color = 'white';
myButton.style.padding = '10px 20px';
myButton.addEventListener('click', () => alert('Button clicked!'));

// Access elements by class name
const messages = document.getElementsByClassName('message');
for (let msg of messages) {
    msg.style.color = 'blue';
    msg.style.fontWeight = 'bold';
}

// Use CSS selectors
const container = document.querySelector('.container');
container.style.border = '2px solid #ccc';
container.style.padding = '20px';

    </script>
</body>
</html>

✅ As you can see:

Elements.myButton.update(...) → replaced by document.getElementById("myButton") then manually setting textContent, style, and addEventListener.

Collections.ClassName.message.update(...) → replaced by document.getElementsByClassName("message") loop and applying styles.

Selector.query(".container").update(...) → replaced by document.querySelector(".container") and applying styles directly.

The library basically:

Removes boilerplate (like looping over collections).

Unifies updates (styles, attributes, listeners) into a single .update() call.

Makes imperative DOM operations more declarative and concise.

Improved Readability

Compare this: Plain Vanilla JS:

   <script>
const myButton = document.getElementById('myButton');
myButton.textContent = 'Enhanced Button!';
myButton.style.backgroundColor = '#007bff';
myButton.style.color = 'white';
myButton.style.padding = '10px 20px';
myButton.addEventListener('click', () => alert('Button clicked!'));

</script>

dom-helpers (declarative style):

<script>
Elements.myButton.update({
   textContent: 'Enhanced Button!',
   style: { backgroundColor: '#007bff', color: 'white', padding: '10px 20px' },
   addEventListener: { click: () => alert('Button clicked!')}
   });

</script>

Simplicity Comparaison

Plain Vanilla js

<script>
    const messages = document.getElementsByClassName('message');
for (let msg of messages) {
    msg.style.color = 'blue';
    msg.style.fontWeight = 'bold';
}
</script>

with dom helpers

<script>
    Collections.ClassName.message.update({
            style: { color: 'blue', fontWeight: 'bold' }
        });
</script>

ES6 Module Import

import { Elements, Collections, Selector } from '@giovanni1707/dom-helpers';

// Use the helpers
Elements.myButton.update({
    textContent: 'Click Me!',
    style: { backgroundColor: '#007bff' }
});

CommonJS

const { Elements, Collections, Selector } = require('@giovanni1707/dom-helpers');

🎯 Core Features

1. Elements Helper - ID-Based Access

Access any element by its ID with automatic caching:

// Simple access
const button = Elements.myButton;

// Declarative updates
Elements.myButton.update({
    textContent: 'Click Me!',
    style: {
        backgroundColor: '#007bff',
        color: 'white',
        padding: '10px 20px'
    },
    classList: {
        add: ['active', 'highlighted'],
        remove: ['disabled']
    },
    addEventListener: {
        click: (e) => console.log('Clicked!'),
        mouseenter: (e) => e.target.style.opacity = '0.8'
    }
});

2. Collections Helper - Class/Tag/Name Access

Work with collections of elements efficiently:

// Access by class name
Collections.ClassName.btn.update({
    style: { padding: '8px 16px' },
    classList: { add: 'enhanced' }
});

// Access by tag name
Collections.TagName.p.update({
    style: { lineHeight: '1.6' }
});

// Utility methods
const buttons = Collections.ClassName.btn;
buttons.forEach(btn => console.log(btn.textContent));
const firstButton = buttons.first();
const visibleButtons = buttons.visible();

3. Selector Helper - CSS Selector Access

Use standard CSS selectors:

// Single element
const header = Selector.query('#header');

// Multiple elements
const allButtons = Selector.queryAll('.btn');

// Scoped queries
const modalButtons = Selector.Scoped.withinAll('#modal', '.btn');

4. Bulk Element Creation - NEW in v2.2.1 🎉

Create multiple elements in one declarative call:

// Create multiple elements at once
const elements = createElement.bulk({
    H1: {
        textContent: 'Welcome!',
        style: { color: '#333', fontSize: '28px' }
    },
    P: {
        textContent: 'This is a paragraph',
        style: { color: '#666', lineHeight: '1.6' }
    },
    BUTTON: {
        textContent: 'Click Me',
        style: { padding: '10px 20px', background: '#007bff', color: 'white' },
        addEventListener: ['click', () => alert('Clicked!')]
    }
});

// Access created elements
elements.H1          // The H1 element
elements.P           // The P element
elements.BUTTON      // The button element

// Append all to DOM
document.body.append(...elements.all);

// Or append in custom order
document.body.append(...elements.ordered('BUTTON', 'H1', 'P'));

// Create multiple instances with numbered suffixes
const cards = createElement.bulk({
    DIV_1: { className: 'card', textContent: 'Card 1' },
    DIV_2: { className: 'card', textContent: 'Card 2' },
    DIV_3: { className: 'card', textContent: 'Card 3' }
});

// Helper methods available
elements.count                    // Get total elements
elements.keys                     // Get all element keys
elements.has('H1')               // Check if element exists
elements.get('H1', null)         // Safe retrieval with fallback
elements.forEach((el, key) => {}) // Iterate over elements
elements.map((el, key) => {})    // Map over elements
elements.filter((el, key) => {}) // Filter elements
elements.appendTo('#container')  // Append all to container
elements.updateMultiple({        // Update multiple at once
    H1: { style: { color: 'blue' } },
    P: { style: { fontSize: '16px' } }
});

Why Use Bulk Creation?

Compare traditional approach vs bulk creation:

// ❌ Traditional - Verbose and repetitive
const h1 = document.createElement('h1');
h1.textContent = 'Title';
h1.style.color = 'blue';

const p = document.createElement('p');
p.textContent = 'Description';
p.style.fontSize = '16px';

const div = document.createElement('div');
div.className = 'container';
div.appendChild(h1);
div.appendChild(p);

// ✅ Bulk Creation - Clean and declarative
const elements = createElement.bulk({
    H1: { textContent: 'Title', style: { color: 'blue' } },
    P: { textContent: 'Description', style: { fontSize: '16px' } },
    DIV: { className: 'container' }
});

elements.DIV.append(elements.H1, elements.P);

Learn More:

📚 Available Modules

DOM Helpers includes specialized modules for different use cases:

Core Module (Required)

  • dom-helpers.js - Core functionality with Elements, Collections, and Selector helpers

Optional Modules

  • dom-helpers-storage.js - LocalStorage and SessionStorage helpers
  • dom-helpers-form.js - Advanced form handling utilities
  • dom-helpers-animation.js - Animation and transition helpers
  • dom-helpers-components.js - Component-based architecture
  • dom-helpers-reactive.js - Reactive state management
  • dom-helpers-async.js - Async operations and data fetching

Combined Build

  • dom-helpers-combined.js - All modules in one file

Minified Versions

All modules are available as minified versions in the helpers-min/ directory.

🔄 Fine-Grained Control System

DOM Helpers includes an intelligent fine-grained update system that minimizes unnecessary DOM writes:

// Only updates if value actually changed
Elements.myButton.update({
    textContent: "Click Me"  // ✅ Updates DOM
});

Elements.myButton.update({
    textContent: "Click Me"  // ✅ Skips - already set
});

// Granular style updates - only changed properties
Elements.myDiv.update({
    style: {
        color: "blue",      // ✅ Updates
        fontSize: "16px"    // ✅ Updates
    }
});

Elements.myDiv.update({
    style: {
        color: "blue",      // ✅ Skips - unchanged
        padding: "10px"     // ✅ Updates - new property
    }
});

📊 Performance Benefits

Operation Vanilla JS DOM Helpers Improvement
Element Access O(1) per call O(1) cached Same speed, cached
Batch Updates Multiple writes Single update call 70-80% less code
Event Listeners Manual deduplication Auto-deduped 100% prevention
Style Updates Overwrites all Only changed props ~70% reduction

🎨 Real-World Example

function createInteractiveButton(buttonId) {
    const button = Elements[buttonId];

    if (!button) {
        console.warn(`Button '${buttonId}' not found`);
        return;
    }

    button.update({
        style: {
            padding: '10px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
            transition: 'all 0.3s ease'
        },
        classList: {
            add: ['interactive', 'enhanced']
        },
        addEventListener: {
            click: (e) => {
                e.target.update({
                    classList: { toggle: 'clicked' },
                    style: { transform: 'scale(0.95)' }
                });

                setTimeout(() => {
                    e.target.update({
                        style: { transform: 'scale(1)' }
                    });
                }, 150);
            },
            mouseenter: (e) => {
                e.target.update({
                    style: { 
                        transform: 'translateY(-2px)',
                        boxShadow: '0 4px 8px rgba(0,0,0,0.2)'
                    }
                });
            },
            mouseleave: (e) => {
                e.target.update({
                    style: { 
                        transform: 'translateY(0)',
                        boxShadow: 'none'
                    }
                });
            }
        }
    });
}

// Usage
createInteractiveButton('submitButton');
createInteractiveButton('cancelButton');

🛠️ Browser Compatibility

  • Modern Browsers: Chrome 15+, Firefox 4+, Safari 5+
  • Internet Explorer: IE 9+
  • Mobile: iOS Safari, Chrome Mobile, Android Browser

📖 Documentation

For comprehensive documentation, examples, and API reference, please visit:

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

Built with ❤️ for developers who love vanilla JavaScript but want better DOM manipulation tools.


Ready to transform your DOM manipulation experience? Install DOM Helpers today and start writing cleaner, more maintainable code!

更新履歴

Changelog

All notable changes to DOM Helpers will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[2.3.0] - 2025-01-10

Added

🎉 Bulk Element Creation Feature

  • createElement.bulk(definitions) - Create multiple DOM elements in a single declarative call
  • createElement.update(definitions) - Alias for bulk element creation
  • Support for numbered instances (e.g., DIV_1, DIV_2, DIV_3)
  • Globally exposed createElement function with bulk creation capabilities

Rich Return Object API

  • Direct element access by key (e.g., elements.H1, elements.P)
  • .all getter - Returns all elements as array
  • .toArray(...keys) - Get specific elements as array
  • .ordered(...keys) - Get elements in custom order
  • .count getter - Total number of elements
  • .keys getter - Array of all element keys
  • .has(key) - Check if element exists
  • .get(key, fallback) - Safe element retrieval with fallback
  • .updateMultiple(updates) - Batch update multiple elements
  • .forEach(callback) - Iterate over elements
  • .map(callback) - Map over elements
  • .filter(callback) - Filter elements
  • .appendTo(container) - Append all elements to container
  • .appendToOrdered(container, ...keys) - Append specific elements in order

Documentation

  • Comprehensive Bulk Element Creation Guide (1,500+ lines)
  • Complete API reference with all methods and parameters
  • 6 detailed usage examples (forms, cards, modals, navigation, etc.)
  • 4 advanced techniques (conditional creation, templates, nested components, event-driven updates)
  • 10 best practices for clean, maintainable code
  • 10 common troubleshooting scenarios with solutions
  • Interactive test file with 5 live examples

Changed

  • Updated README.md with bulk element creation documentation
  • Enhanced package description to include bulk creation feature
  • Updated version from 2.2.1 to 2.3.0

Improved

  • Element configuration now supports comprehensive property types:
    • Style objects with camelCase properties
    • ClassList manipulation (add, remove, toggle, replace)
    • Attributes (both object and array formats)
    • Dataset attributes
    • Event listeners (single or multiple)
    • Any DOM property or method

[2.2.1] - 2024-12-XX

Fixed

  • Fine-grained update system improvements
  • Cache management optimizations
  • Event listener deduplication enhancements

Changed

  • Performance optimizations for element access
  • Improved error handling and warnings

[2.2.0] - 2024-11-XX

Added

  • Fine-grained control system for DOM updates
  • Intelligent change detection to minimize DOM writes
  • Event listener auto-deduplication
  • Granular style updates (only changed properties)

Improved

  • 70% reduction in unnecessary DOM operations
  • Better memory management
  • Enhanced caching mechanisms

[2.1.0] - 2024-10-XX

Added

  • Collections helper for class/tag/name-based access
  • Selector helper with CSS selector support
  • Scoped query methods
  • Utility methods for collections (first, last, at, visible, hidden, etc.)

Changed

  • Modular architecture improvements
  • CDN distribution enhancements

[2.0.0] - 2024-09-XX

Added

  • Universal .update() method for all elements and collections
  • Intelligent caching system
  • Auto-cleanup on page unload
  • Comprehensive error handling

Changed

  • BREAKING: Redesigned API for better developer experience
  • BREAKING: Changed module structure

Removed

  • BREAKING: Deprecated old API methods

[1.x.x] - 2024-XX-XX

Initial Releases

  • Core DOM manipulation utilities
  • Basic element access helpers
  • Event handling utilities

Upgrade Guide

Upgrading to 2.3.0 from 2.2.x

No breaking changes! The bulk element creation feature is an addition to the existing API.

New Feature Usage

// New bulk creation feature
const elements = createElement.bulk({
    H1: { textContent: 'Title' },
    P: { textContent: 'Description' },
    BUTTON: { textContent: 'Click Me' }
});

// Access elements
elements.H1      // The H1 element
elements.all     // Array of all elements

// Append to DOM
document.body.append(...elements.all);

CDN Update

Update your CDN link to use the latest version:

<!-- Update from 2.2.1 to 2.3.0 -->
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@2.3.0/dist/dom-helpers.min.js"></script>

<!-- Or use @latest for automatic updates -->
<script src="https://cdn.jsdelivr.net/npm/@giovanni1707/dom-helpers@latest/dist/dom-helpers.min.js"></script>

NPM Update

npm update @giovanni1707/dom-helpers

Migration Guides

From 1.x to 2.x

Please refer to the migration guide for detailed instructions.


Support


Legend:

  • 🎉 New Feature
  • ✨ Enhancement
  • 🐛 Bug Fix
  • 🔒 Security
  • 📖 Documentation
  • ⚠️ Deprecation
  • 💥 Breaking Change