Skip to content

Instantly share code, notes, and snippets.

@ricealexander
Last active December 17, 2019 16:11
Show Gist options
  • Save ricealexander/e4c1d06ee72986d41b2748c19e983765 to your computer and use it in GitHub Desktop.
Save ricealexander/e4c1d06ee72986d41b2748c19e983765 to your computer and use it in GitHub Desktop.
query() helper function
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