Home

Awesome

el-js

Utility function for generating HTML/XML DOM trees in the browser.

API

The library exposes a single function, el(), which returns a node with the given name. The rest are var-args, so that:

For convenience, falsy values in the list of children are ignored.

There's three special cases for the name argument:

Examples

Creating elements, comments and text nodes:

el('p',
    el('<!', 'this is a comment'),
    el('a', 'Click here', {
        href: '#some-location'
    }),
    el('', 'Text after link')
);

produces:

<p>
    <!--this is a comment-->
    <a href="#some-location">Click here</a>
    Text after link
</p>

Mapping arrays into child elements, and filtering by returning falsy values (in this case undefined):

el('ul',
    [ 1, 2, 3, 4, 5 ].map(function(i) {
        if (i % 2) return el('li', i);
    })
);

produces:

<ul>
    <li>1</li>
    <li>3</li>
    <li>5</li>
</ul>

Appending children into existing elements:

el(document.querySelector('#existing-root'),
    el('p', 'New node added under root')
);

produces:

<div id="existing-root">
    <p>Possible previous content</p>
    <p>New node added under root</p>
</div>

Acknowledgements

Hand-crafted by @jareware of jrw.fi, with the loving support of Futurice.

License

The MIT license

History

Because el-js is so tiny, it was originally published in 2014 as just a gist. This repository and an npm-presence were added for convenience.