A tiny (520 bytes) and fast DOM manipulation library for use with plain JavaScript
Search the document for an element with a particular CSS selector
selector (string)
- the CSS selector to match against
(HTMLElement)
the first matching element
// <div class="content">
// <div id="myDiv">
// We want to add a click event listener to this div
// </div>
// </div>
const myDiv = el.el("#myDiv")
myDiv.addEventListener("click", event => alert("myDiv was clicked"))
Create a new HTML DOM element
tag (string)
- the type/tag of the element to constructattributes (Object)
-{"key": "value", ...}
attributes the element should havechildren (HTMLElement[] | string[])
- elements to append to the new element as children. Strings are automatically converted to Text nodes
(HTMLElement)
the newly created element
// Create HTML DOM element equivalent to
// <div class="content">
// <p>A paragraph with <a href="http://example.com/">a link</a></p>
// </div>
const contentDiv = el.h("div", {class: "content"}, [
el.h("p", {}, [
"A paragraph with ", el.h("a", {href: "http://example.com/"}, ["a link"]
]
])
Append child elements to another element
el (HTMLElement)
- the parent elementchildren (HTMLElement[] | string[])
- elements to append toel
as children. Strings are automatically converted to Text nodes
// Before:
// <div id="myDiv">
// </div>
const myDiv = el.el("#myDiv")
el.append(myDiv, [
el.h("p", {}, ["Hello, World!"])
])
// After:
// <div id="myDiv">
// <p>Hello, World!</p>
// </div>
Search the document for an element with a particular CSS selector and delete all of its child elements
selector (string)
- the CSS selector to match against
(HTMLElement)
the first matching element
// Before:
// <div id="myDiv">
// <p>Hello, World!</p>
// </div>
const myDiv = el.clear("#myDiv")
// After:
// <div id="myDiv">
// </div>
Delete all of the given element's child elements
el (HTMLElement)
- the parent element
el (HTMLElement)
// Before:
// <div id="myDiv">
// <p>Hello, World!</p>
// </div>
const myDiv = el.el("#myDiv")
el.clearElement(myDiv)
// After:
// <div id="myDiv">
// </div>
Measuring operations per second (higher is better) in Chrome 59.0.3071 / Windows 10 0.0.0
Select (Ops/sec) | Clear (Ops/sec) | Create/Append (Ops/sec) | |
---|---|---|---|
elemental-js | 12,351,821 | 76,287,755 | 150,784 |
jQuery 3.2 | 2,081,431 | 2,191,646 | 59,799 |
innerHTML | 442,922 | 86,772 |
const myDiv = el.el("#myDiv")
const myDiv = $("#myDiv")
el.clearElement(myDiv)
myDiv.empty()
myDiv.innerHTML = ""
el.append(myDiv, [
"testing ",
el.h("a", {href: "http://example.com"}, ["link"])
])
myDiv.html('testing <a href="http://example.com">link</a>');
myDiv.innerHTML = 'testing <a href="http://example.com">link</a>'