Created
December 6, 2013 01:55
-
-
Save dalgard/7817354 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