Skip to content

Instantly share code, notes, and snippets.

@dalgard
Created December 6, 2013 01:55
Show Gist options
  • Save dalgard/7817354 to your computer and use it in GitHub Desktop.
Save dalgard/7817354 to your computer and use it in GitHub Desktop.
Efficient wrapper for document.querySelectorAll
// Always return an array of DOM elements
function queryAll(selector) {
var id_sel = selector.match(/^#([\w-]*)$/),
class_sel = !id_sel && selector.match(/^\.([\w-]+)$/),
tag_sel = !class_sel && selector.match(/^[\w-]+$/);
if (id_sel) {
var elem = document.getElementById(id_sel[1]);
return (elem ? [elem] : []); // Always return an array
}
if (class_sel) {
var elems = document.getElementsByClassName(class_sel[1]);
return toArray(elems);
}
if (tag_sel) {
var elems = document.getElementsByTagName(selector);
return toArray(elems);
}
return toArray(document.querySelectorAll(selector));
// Convert array-like collections to arrays (hoisted)
function toArray(coll, from_index) {
return Array.prototype.slice.call(coll, from_index);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment