Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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