Skip to content

Instantly share code, notes, and snippets.

@shakahl
Forked from dalgard/queryAll.js
Created March 3, 2024 15:45
Show Gist options
  • Save shakahl/93b599228ce56c19753de4e65a286a13 to your computer and use it in GitHub Desktop.
Save shakahl/93b599228ce56c19753de4e65a286a13 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