Skip to content

Instantly share code, notes, and snippets.

@nash403
Created December 7, 2016 15:01
Show Gist options
  • Save nash403/893c522c083950de58aa233036704056 to your computer and use it in GitHub Desktop.
Save nash403/893c522c083950de58aa233036704056 to your computer and use it in GitHub Desktop.
A good compromise between querySelectorAll and getElementsBy[...] functions !
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