Lightweight DOM Manipulation Library for Modern Web Apps – Domate

Category: Javascript | May 7, 2025
Author:vugarsafarzada
Views Total:0 views
Official Page:Go to website
Last Update:May 7, 2025
License:MIT

Preview:

Lightweight DOM Manipulation Library for Modern Web Apps – Domate

Description:

Domate is a lightweight JavaScript library that enables programmatic manipulation of DOM elements for building dynamic web interfaces.

This library transforms standard HTML elements into powerful, programmable objects with an elegant, chainable API. Useful for projects where you want to minimize HTML and CSS footprint and drive the presentation layer almost entirely from script.

Features:

  • Object-Oriented DOM Wrappers: Uses DOMElement and Container classes for structured manipulation.
  • Versatile Styling Utilities: Helper methods for pixel, percentage, vw, vh units, plus a setStyle for bulk CSS properties.
  • Sequential Animation Queue: A built-in animationQueue method to run a series of function-based animations with timing controls.
  • Child Element Management: The Container class provides simple addChild and removeChild methods.
  • Lightweight & Dependency-Free: No external libraries needed; just plain JavaScript.
  • Developer-Friendly API – Chainable methods and predictable patterns make complex manipulations simple.

How to use it:

1. Install Domate and import it into your project.

# NPM
$ npm install domate
import { Container, DOMElement } from "domate";
// OR
import { Container, DOMElement } from "./dist/script.js";

2. Here’s a simple example of creating a centered, animated div:

// Create a container using the document body
const body = new Container();
// Create utility constants for readable units
const { pixel, percentage, viewHeight, viewWidth } = body;
// Set up the body container styles
body.setWidth(viewWidth(100))
  .setHeight(viewHeight(100))
  .setStyle({
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      overflow: 'hidden'
  });
// Create an app container with a specific element
const app = new Container(document.getElementById('app'));
// Configure the app container
app.setSize(pixel(200))
 .setStyle({borderRadius: percentage(100)})
 .setBGColor('#3498db')
 .setTransitionDuration(0.5);

3. One of Domate’s standout features is its animation queue system:

// Create a pulsing effect
let size = 100;
let growing = true;
body.animationQueue([
  // First animation state
  () => {
    app.setSize(pixel(size));
    app.setBGColor('#3498db');
  },
  // Second animation state
  () => {
    app.setSize(pixel(size));
    app.setBGColor('#e74c3c');
  }
], {
  speed: 1000,       // Complete cycle in 1000ms
  stopLoop: false,   // Loop indefinitely
  every: () => {     // Run after each animation step
    if (growing) {
      size += 10;
      if (size >= 200) growing = false;
    } else {
      size -= 10;
      if (size <= 100) growing = true;
    }
  }
});

4. API methods:

DOMElement Methods:

  • pixel(value): Returns value as px string (e.g., 100px).
  • percentage(value): Returns value as % string (e.g., 50%).
  • viewWidth(value) / viewHeight(value): For vw and vh units.
  • seconds(value): For time values like 1s. (Note: The setTransitionDuration expects milliseconds, but this method converts a number to a string with ‘s’ suffix, which is typically used for CSS. The library itself uses this.seconds(value) for transitionDuration in animationQueue after dividing milliseconds by 1000. Be mindful of this for direct usage.)
  • setId(id): Sets the element’s ID.
  • setBGColor(color = "#000"): Sets background.
  • setWidth(value = this.pixel(100)) / setHeight(value = this.pixel(100)): Set dimensions.
  • setSize(value): Sets both width and height.
  • setPosition({ x = 0, y = 0 }): Sets top and left. Default coordinates are provided if an invalid object is passed.
  • setTransitionDuration(value = 1000): Sets transition-duration in milliseconds (it converts to seconds internally).
  • setText(value): Sets innerText.
  • setHTML(value = []): Sets innerHTML. Expects an array of HTMLElement objects. It filters out non-HTMLElements, which is a nice touch.
  • setTitle(value): Sets the title attribute (tooltip).
  • setStyle(styles = {}): Apply a batch of CSS styles from an object (e.g., { display: 'flex', alignItems: 'center' }).
  • animationQueue(order = [], options = { stopLoop: false, speed: 1000, every: () => {} }):
    • order: An array of functions. Each function typically manipulates the element’s style.
    • options.stopLoop: Boolean, false by default (loops indefinitely).
    • options.speed: Total time in milliseconds for one pass through the order array.
    • options.every: A callback function executed after each step in the order.

Container Methods (extends DOMElement):

  • constructor(element = document.getElementsByTagName("body")[0]): Can wrap an existing element or defaults to document.body.
  • addChild(child): Appends an HTMLElement to this container.
  • removeChild(index): Removes a child at a specific index from its internal children array and the DOM.

FAQs

Q: How does Domate handle event listeners?
A: Domate itself doesn’t provide methods for event handling. You’d interact directly with the underlying DOM element: myDomElement.element.addEventListener('click', () => { /* ... */ });. This keeps the library focused.

Q: Can I use Domate to manage elements not created by it?
A: Absolutely. You can pass an existing DOM element to the constructor: const myElem = new DOMElement(document.getElementById('my-existing-div'));. The Container constructor even defaults to document.body if no element is given.

Q: What’s the performance of animationQueue?
A: The JavaScript part (calling your functions via setTimeout) is generally fast. The visual smoothness depends on the CSS transitions. If your order functions do very heavy DOM manipulation or calculations, that could be a bottleneck. The speedPerItem determines the transition-duration; very short durations might not be perceptible. Applying transition-duration to all children ([...this.element.children].forEach(...)) on each step could be a minor hit if there are hundreds of direct children with their own transitions to manage, but for typical use cases, it’s fine.

Q: Is Domate a replacement for a framework like React or Vue?
A: Not really. Domate is much lower-level. It helps with direct DOM manipulation and styling. Frameworks offer component models, state management, declarative rendering, and a Virtual DOM, which are for building larger, more complex applications. You could build a whole app UI with Domate, but you’d be managing state and structure manually.

Q: The setHTML method takes an array of HTMLElements. What if I have an HTML string?
A: setHTML is specific about its input to avoid innerHTML issues with non-element content. If you have an HTML string, you’d first need to parse it into HTMLElements (e.g., using DOMParser or by setting innerHTML on a temporary disconnected element and then grabbing its children) before passing them to setHTML. Or, if you trust your HTML string, you could just do myDomElement.element.innerHTML = myHtmlString;.

You Might Be Interested In:


Leave a Reply