-
-
Save shakahl/93b599228ce56c19753de4e65a286a13 to your computer and use it in GitHub Desktop.
Efficient wrapper for document.querySelectorAll
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
// 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