slct
A native DOM selection engine with cache built in.
584 B
. ⚡️
Usage
Using npm:
$ npm install --save slct
The UMD build is also available on unpkg:
API
slct(query, invalidate)
query
A normal query string with an identifier.
The substring after the identifier will be passed into the native DOM methods.
Type: String
// Supported Identifiers// '.' = getElementsByClassName// '#' = getElementById// '%' = getElementsByTagName// '@' = getElementsByName// '?' = querySelector// '*' = querySelectorAll // Examples:; // document.getElementsByClassName('.links'); // document.getElementById('logo'); // document.getElementsByTagName('li'); // document.getElementsByName('random'); // document.querySelector('div'); // document.querySelectorAll('.links');
invalidate
To invalidate a selector and re-cache it.
Type: Boolean
Default: false
Motivation
Often, we have to write code that looks like this:
/** * 1. * Here, we are caching the selector for better performance. * This prevents any additional DOM lookup when the selector * is needed again. * * Also, notice the very verbose DOM API's. Who wants to write * `document.querySelectorAll` over and over again? */const links = document;const logo = document;const li = document;const name = document;const blue = document; /** * 2. * Since NodeList is not Array-like, we can't call `forEach` directly, * and this results in the following code. */forEach;
What if we can write code that looks like this ?
/** * slct automatically caches the selector and convert NodeList * into Array-like, thus resulting in less boilerplate code. */; ; /** * To invalidate the selector and re-cache it. */; /** * Also, it comes with identifiers so that you don't have to write * those verbose DOM API's. * Read the API section for more info. */ // document.getElementsByName('random'); // document.querySelector('div');
License
MIT © Jonathan Chan