Last active
December 17, 2019 16:11
-
-
Save ricealexander/e4c1d06ee72986d41b2748c19e983765 to your computer and use it in GitHub Desktop.
query() helper function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const query = (selector, source = document) => { | |
if (isElement(selector)) return selector | |
if (typeof selector !== 'string') { | |
throw new TypeError(`First argument must be a string. Instead got ${typeof selector}`) | |
} | |
if (!isElement(source)) { | |
throw new TypeError(`Second argument must be a Node/NodeList. Instead got ${source}`) | |
} | |
const nodes = source.querySelectorAll(selector) | |
return (nodes.length > 1) ? nodes : nodes[0] | |
} | |
// JavaScript Query Helper Function | |
/// alternative to document.querySelector() and document.querySelectorAll() | |
/// this coerces a selector into a Node/NodeList | |
/// returns a node if a single element matches the selector | |
/// returns a nodeList if multiple elements match the selector | |
/// a second argument allows a user to specify a source to query from | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment