Dynamic DOM Creation & Manipulation With TinyJS

Category: Javascript , Recommended | October 3, 2024
Author:victorqribeiro
Views Total:15 views
Official Page:Go to website
Last Update:October 3, 2024
License:MIT

Preview:

Dynamic DOM Creation & Manipulation With TinyJS

Description:

TinyJS is a small JavaScript library that helps you easily create HTML elements on the fly. It lets you build any standard HTML tag using JavaScript, set attributes, add content, and even select elements from your web page just like jQuery’s $selector. This makes working with the Document Object Model (DOM) much simpler.

This library can be helpful when you need to build parts of your webpage using JavaScript code rather than writing HTML directly. For example, you could use TinyJS to:

  • Generate a list of products from an online store.
  • Build a form with input fields and buttons.
  • Create custom pop-up messages or notifications.
  • And more

How to use it:

1. Download the TinyJS package and insert the main script into your document.

<script src="tiny.js"></script>

2. TinyJS allows you to use any standard HTML tag name as a function to create the corresponding element. You can pass properties as the first argument (if needed) and the element content as subsequent arguments.

Here’s an example of creating a styled button:

const myButton = button(
  {
    style: {
      backgroundColor: '#222', 
      color: '#fff',
      padding: '20px',
      /* more CSS styles here */
    }, 
    onclick: () => alert('Clicked')}, 
    'My Button'
);
document.body.appendChild(myButton);

This code makes a dark button with white text that shows an alert when clicked.

3. TinyJS provides two convenient functions for selecting elements from the DOM:

  • $: This function works just like document.querySelector. It allows you to select a single element based on a CSS selector.
  • $$ or $all: This function works like document.querySelectorAll. It returns an array of all elements that match the given CSS selector.
const myEle = $('#container');
const items = $$('.item');
items.forEach(item => {
  console.log(item);
});

How it works:

Deep Property Assignment: TinyJS handles nested properties (like the style object in the button example) using a recursive function called assignDeep. This ensures that you can set properties within properties easily.

Element Creation: TinyJS iterates through a list of all standard HTML tag names and creates a function for each one. These functions are responsible for creating the element, assigning properties, and appending child content.

DOM Selection Wrappers: TinyJS provides the $, $$, and $all functions as convenient wrappers around the built-in DOM selection methods, making it easier to work with the DOM.

Changelog:

v1.0.2 (10/03/2024)

  • Bugfix

You Might Be Interested In:


Leave a Reply