DOM queries that always return an array
npm install tealight
DOM queries that always return an array.
Modern browsers enable us to perform DOM queries natively, e.g:
``js`
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:
`js
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.
`js`
tealight(".cookie").forEach(cookie => {
// ...
});
A simple and fast way to get started is to include this script on your page:
`html`
This will create the global variable tealight.
`bash`
$ npm install tealight
#### CommonJS
`js`
const tealight = require("tealight");
#### ES2015
`js`
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:
`html`
string targets will be used as CSS selectors.
` tealight(node); tealight(nodeList); tealight(array);js
tealight("#jar");
// => [ ]
``js`
tealight(".cookie");
// => [ HTMLElement$3
targets will simply be wrapped in an Array`js
const node = document.querySelector("#jar");
// => [ ]
`HTMLCollection$3
arguments will be converted to Array.`js`
const nodeList = document.querySelectorAll(".cookie");
// => [ Array$3
targets will be filtered, leaving only HTMLElement`js
let node = document.querySelector("#jar");
let array = [node, null, ".cookie"];
// => [