Skip to content

Instantly share code, notes, and snippets.

@nenadom
Last active February 22, 2017 14:31
Show Gist options
  • Save nenadom/80c32597ecf689b59e6cec6b6fdd45c2 to your computer and use it in GitHub Desktop.
Save nenadom/80c32597ecf689b59e6cec6b6fdd45c2 to your computer and use it in GitHub Desktop.
A convenience wrapper around querySelector/querySelectorAll, with a transform function to turn NodeLists into arrays.
/* jshint -W033, -W097 */
/* globals document, Element */
(function() {
"use strict";
function query(es, s) {
return _q(es, s, "querySelector")
}
function queryAll(es, s) {
return _q(es, s, "querySelectorAll")
}
/**
* Create an array from enumerable elements in a node list.
* Useful if you want to map it, slice it, etc.
* @param {NodeList} nodeList A selection of nodes, such as from document.querySelectorAll.
* @return {Array}
*/
function nodeArray(nodeList) {
return Array.prototype.slice.call(nodeList)
}
/**
* Function internals for querySelector/querySelectorAll.
* 1. Exit if qs/qsA not supported.
* 2. If multiple arguments received, try selecting descendants
* of 1st parameter (either an HTML element (3.) or string (4.) will work),
* assume second argument is a string in that case.
* 5. If no results yet and `es` is a string, query it.
*
* @param {Element|String} es Either an HTML element or a selector
* @param {String} s Selector
* @param {String} queryFunction "querySelector"|"querySelectorAll"
* @return {*}
*/
function _q(es, s, queryFunction) {
var root = document
var el
var r
if (typeof document[queryFunction] === "undefined") return // 1.
if (arguments.length > 1 && typeof s === "string") { // 2.
if (es instanceof Element) { root = es } // 3.
if (typeof es === "string") { // 4.
el = document.querySelector(es)
root = el ? el : root
}
r = root[queryFunction](s)
}
if (!r && typeof es === "string") { // 5.
r = root[queryFunction](es)
}
if (r) { return r.length ? nodeArray(r) : r }
}
// export to global scope
window.query = query
window.queryAll = queryAll
window.nodeArray = nodeArray
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment