Created
December 7, 2016 15:01
-
-
Save nash403/893c522c083950de58aa233036704056 to your computer and use it in GitHub Desktop.
A good compromise between querySelectorAll and getElementsBy[...] functions !
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
function query(selector, context) { | |
context = context || document; | |
// Redirect simple selectors to the more performant function | |
if (/^(#?[\w-]+|\.[\w-.]+)$/.test(selector)) { | |
switch (selector.charAt(0)) { | |
case '#': | |
// Handle ID-based selectors | |
return [context.getElementById(selector.substr(1))]; | |
case '.': | |
// Handle class-based selectors | |
// Query by multiple classes by converting the selector | |
// string into single spaced class names | |
var classes = selector.substr(1).replace(/\./g, ' '); | |
return [].slice.call(context.getElementsByClassName(classes)); | |
default: | |
// Handle tag-based selectors | |
return [].slice.call(context.getElementsByTagName(selector)); | |
} | |
} | |
// Default to `querySelectorAll` | |
return [].slice.call(context.querySelectorAll(selector)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment