npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cypherpotato/el

v0.3.0

Published

a tiny tool to create HTMLElements on the fly

Downloads

291

Readme

el.js

This 3,9 Kb (1,8 Kb gzipped) tool is a tool for creating HTML elements. It is a functional alternative to document.createElement().

Installation

Include the import via CDN in the <head> of your HTML:

<script src="https://unpkg.com/@cypherpotato/el/dist/el.min.js"></script>

If you are using a package manager, you can install the package with:

npm install @cypherpotato/el

And use it as:

import el from '@cypherpotato/el';

Usage

el("tag-name", ... [children|attributes]);

The el() method is used with one or more arguments. The first argument is always the tag of the HTML element, and the other elements are added as children of the element. If one of the arguments is an object, the el function will attempt to assign the object's attributes to the element.

The return of the el function is always an HTMLElement. No wrapper is created. You can use the return directly to add elements with document.appendChild.

Emmet is partially supported. You can use it to create elements with attributes, IDs, or classes. It is not possible to create more than one element with el, so do not try to use commas when creating elements. The table below of examples illustrates the use of the el() method.


Basic usage:

el("div");
// -> <div></div>

el("div.container.fluid");
// -> <div class="container fluid"></div>

el("div#myDiv");
// -> <div id="myDiv"></div>

el("div[foo=bar].mt-3");
// -> <div foo="bar" class="mt-3"></div>

Event listeners example:

el("div", {
    id: "myDiv",
    class: [ "container", "fluid" ],
    onClick: function(event) {
            console.log("Clicked on the div!");
        }
    }, "Click me!");
<div class="container fluid" id="myDiv">
    Click me!
</div>

Input example:

el("input", {
    type: "text",
    name: "userName",
    placeholder: "Type something..."});
<input type="text" name="userName" placeholder="Type something...">

Nested childrens:

el(".form-group",
    el("label", { for: "cheese" }),
    el("input[type=checkbox]#cheese"));
<div class="form-group">
    <label for="cheese">
        I want cheese
    </label>
    <input id="cheese" type="checkbox">
</div>

Mixed content:

el("custom-tag", "inner text", el("span", "inner span"));
<custom-tag>
    inner text
    <span>
        inner span
    </span>
</custom-tag>

Custom attributes:

el("div", {
    $customAttribute: "custom value",
    '$data-custom-text': true});
<div customattribute="custom value" data-custom-text="true">
</div>

Custom components:

const ul = function() { return el('ul', { class: "custom-ul" }, ...arguments); }
const li = function() { return el('li', ...arguments); }

ul(
    li("Apple"),
    li("Limon"),
    li("Banana"));
<ul class="custom-ul">
    <li>Apple</li>
    <li>Limon</li>
    <li>Banana</li>
</ul>

Custom components with arguments:

const Card = function (cardTitle, ...children) {
    return el("div.card",
        el("div.card-header", cardTitle),
        el("div.card-body", ...children));
};

const cardElement = Card("Paris",
    el("p", "Paris is the capital of France."),
    el("img", { src: "https://picsum.photos/200" }),
    el("a", { href: "https://en.wikipedia.org/wiki/Paris" }, "Wikipedia"));
<div class="card">
    <div class="card-header">Paris</div>
    <div class="card-body">
        <p>
            Paris is the capital of France.
        </p>
        <img src="https://picsum.photos/200">
        <a href="https://en.wikipedia.org/wiki/Paris">
            Wikipedia
        </a>
    </div>
</div>

Raw template rendering:

el("div", el.raw(`
    <p>This template will be parsed as HTML</p>
    <button>But it is vulnerable to XSS attacks</button>
`));
<div>
    <p>This template will be parsed as HTML</p>
    <button>But it is vulnerable to XSS attacks</button>
</div>

Unsafe/safe text escaping:

const safeText = "<p>This is secure.</p> <script>alert('XSS')</script>";
const unsafeText = el.raw("<p>This is unsafe.</p> <script>alert('XSS')</script>");

el(".safe-text", safeText);
el(".unsafe-text", unsafeText);
<div class="safe-text">
    &lt;p&gt;This is secure.&lt;/p&gt; &lt;script&gt;alert('XSS')&lt;/script&gt;
</div>
<div class="unsafe-text">
    <p>This is unsafe.</p><script>alert('XSS')</script>
</div>

Defined components

You can define custom components with el and later use them as elements. These components are "swapped" with their original elements, maintaining their scope and placing a new component in their place.

See the example below. It registers a component called city-card that receives two attributes: city-name, city-description. These attributes are defined directly on the element being created.

<body>
    <city-card city-name="Paris" city-description="The capital of France">
        <p>Paris is the capital of France.</p>
        <img src="https://picsum.photos/200" alt="Paris">
        <a href="https://en.wikipedia.org/wiki/Paris">See more on Wikipedia</a>
    </city-card>
</body>

Then, we define our component and the action that will generate another element from the original <city-card>:

el.defineComponent('city-card', attr =>
    el('.card',
        el('.card-header', attr['city-name']),
        el('.card-description', attr['city-description']),
        el('.card-body', ...attr.slot))); // slot contains the children of the original element

And the result, as soon as the page is loaded, all <city-card> will be replaced by the components:

<div class="card" city-name="Paris" city-description="The capital of France">
    <div class="card-header">Paris</div>
    <div class="card-description">The capital of France</div>
    <div class="card-body">
        <p>
            Paris is the capital of France.
        </p>
        <img src="https://picsum.photos/200" alt="Paris">
        <a href="https://en.wikipedia.org/wiki/Paris">
            See more on Wikipedia
        </a>
    </div>
</div>

All attributes of the original element are preserved in the subsequently created element. Therefore, you will be able to reuse the ID, classes, styles, etc.

Components defined with el.defineComponent are only replaced in three situations:

  • When the page is loaded for the first time on document.DOMContentLoaded.
  • When you try to create a component with el().
  • When you call el.scanComponents(), which replaces all components defined on the page.

These elements can also have state, but they are not natively "reactive." The example below illustrates a counter:

el.defineComponent('counter', function (attr) {
    var count = attr.start ?? 0;
    var textElement = el('p', getCurrentText());

    function getCurrentText() {
        return `Current count: ${count}`;
    }

    function increment() {
        count++;
        textElement.innerText = getCurrentText();
    }

    function decrement() {
        count--;
        textElement.innerText = getCurrentText();
    }

    return el('.counter',
        el('button', { onClick: increment }, 'Increment'),
        el('button', { onClick: decrement }, 'Decrement'),
        textElement);
});

const myCounter = el('counter', { start: 10 });
document.body.appendChild(myCounter);

In the code above, you will have a counter that updates whenever a button is pressed.

There may be cases where some components are not replaced. This can happen if the component was created outside the el() function or after the page has loaded. If you have another library that also creates elements on the page, you can create a MutationObserver to observe all new elements and replace them if necessary.

function observeComponents() {
    const callback = (mutationList, _) => {
        for (const mutation of mutationList) {
            if (mutation.type === "childList") {
                el.scanComponents();
            }
        }
    };

    const observer = new MutationObserver(callback);
    observer.observe(document.body, { attributes: true, childList: true, subtree: true });
}

observeComponents();

In the code above, observeComponents() will observe whenever a new element is created or removed from the DOM, and when that happens, it will call el.scanComponents(), which will replace all components defined with el.defineComponent().

These components should not be confused with Web Components (custom elements) or reactive components like those in React. Instead, el.defineComponent is a helper that replaces native elements with other native elements.