Last active
February 29, 2016 09:44
-
-
Save abhidilliwal/4df57e1041f43e6e6793 to your computer and use it in GitHub Desktop.
JavaScript Querying elements efficiently, fork from Zepto.js
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
// 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