https://github.com/jlmakes/tealight
DOM queries that always return an array.
https://github.com/jlmakes/tealight
dom-library query
Last synced: 23 days ago
JSON representation
DOM queries that always return an array.
- Host: GitHub
- URL: https://github.com/jlmakes/tealight
- Owner: jlmakes
- License: mit
- Created: 2017-11-15T17:44:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2021-01-01T04:10:58.000Z (over 4 years ago)
- Last Synced: 2025-03-27T02:51:17.912Z (about 1 month ago)
- Topics: dom-library, query
- Language: JavaScript
- Homepage:
- Size: 44.9 KB
- Stars: 3
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
![]()
![]()
DOM queries that always return an array.
## Introduction
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 => {
// ...
});
```
## Installation
### Browser
A simple and fast way to get started is to include this script on your page:
```html
```
This will create the global variable `tealight`.
### Module
```bash
$ npm install tealight
```#### CommonJS
```js
const tealight = require("tealight");
```#### ES2015
```js
import tealight from "tealight";
```
## Usage
`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
```
### `tealight(target: string): Array`
`string` targets will be used as CSS selectors.
```js
tealight("#jar");
// => []
``````js
tealight(".cookie");
// => [ , , ]
```
### `tealight(target: HTMLElement): Array`
`HTMLElement` targets will simply be wrapped in an `Array`
```js
const node = document.querySelector("#jar");tealight(node);
// => []
```
### `tealight(target: HTMLCollection) : Array`
`HTMLCollection` arguments will be converted to `Array`.
```js
const nodeList = document.querySelectorAll(".cookie");tealight(nodeList);
// => [ , , ]
```
### `tealight(target: Array): Array`
`Array` targets will be filtered, leaving only `HTMLElement`
```js
let node = document.querySelector("#jar");
let array = [node, null, ".cookie"];tealight(array);
// => []
```
---
Copyright 2020 Julian Lloyd
Open source under the [MIT License](https://github.com/jlmakes/tealight/blob/master/LICENSE).