DOM queries that always return an array.
Modern browsers enable us to perform DOM queries natively, e.g:
let cookies = document.querySelectorAll(".cookie");But we all want to loop over the returned elements. So in practice, we’ve got to do a little more work, particularly converting the resulting NodeList to an array, e.g:
let cookies;
try {
let query = document.querySelectorAll(".cookie");
cookies = Array.prototype.slice.call(query);
} catch (err) {
console.error(err.message);
}
cookies.forEach(cookie => {
// ...
});Tealight provides a familiar API to perform native queries, without the extra work.
tealight(".cookie").forEach(cookie => {
// ...
});A simple and fast way to get started is to include this script on your page:
<script src="https://unpkg.com/tealight"></script>This will create the global variable tealight.
$ npm install tealightconst tealight = require("tealight");import tealight from "tealight";tealight accepts a single argument target and will always return an array of 0 or more DOM nodes.
For the examples below, we will query against this HTML fragment:
<div id="jar">
<div class="chocolate-chip cookie"></div>
<div class="peanut-butter cookie"></div>
<div class="short-bread cookie"></div>
</div>string targets will be used as CSS selectors.
tealight("#jar");
// => [ <div#jar> ]tealight(".cookie");
// => [ <div.chocolate-chip.cookie>, <div.peanut-butter.cookie>, <div.short-bread.cookie> ]HTMLElement targets will simply be wrapped in an Array
const node = document.querySelector("#jar");
tealight(node);
// => [ <div#jar> ]HTMLCollection arguments will be converted to Array.
const nodeList = document.querySelectorAll(".cookie");
tealight(nodeList);
// => [ <div.chocolate-chip.cookie>, <div.peanut-butter.cookie>, <div.short-bread.cookie> ]Array targets will be filtered, leaving only HTMLElement
let node = document.querySelector("#jar");
let array = [node, null, ".cookie"];
tealight(array);
// => [ <div#jar> ]Copyright 2020 Julian Lloyd
Open source under the MIT License.