Skip to content

Instantly share code, notes, and snippets.

@abhidilliwal
Last active February 29, 2016 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhidilliwal/4df57e1041f43e6e6793 to your computer and use it in GitHub Desktop.
Save abhidilliwal/4df57e1041f43e6e6793 to your computer and use it in GitHub Desktop.
JavaScript Querying elements efficiently, fork from Zepto.js
// source/credits: https://github.com/madrobby/zepto/blob/master/src/zepto.js
// usage query(document.body, '.cls .childrens')
function query(element, selector){
var found,
maybeID = selector[0] == '#',
maybeClass = !maybeID && selector[0] == '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
isSimple = /^[\w-]*$/.test(nameOnly);
return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById
( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
(element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] :
[].slice.call(
isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
element.getElementsByTagName(selector) : // Or a tag
element.querySelectorAll(selector) // Or it's not simple, and we need to query all
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment