Created
July 31, 2015 09:18
-
-
Save myurasov/99761a62b2c5ba0c9aba to your computer and use it in GitHub Desktop.
Simpe element querying by class/id
This file contains hidden or 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 (global) { | |
function query(selector) { | |
if (!selector) return []; | |
// format selector (remove double spaces, convert to lower case), convert into array | |
selector = selector.toLowerCase().trim().replace(/ +/g, ' ').split(' '); | |
return _query(selector, document.body, []); | |
} | |
function _query(selector, root, result) { | |
if (selector.length > 0) { | |
var curSelector = selector[0]; | |
var curResult = []; | |
var i = 0; | |
if (curSelector.charAt(0) === '.') { | |
var className = curSelector.substr(1); | |
for (i = 0; i < root.children.length; i++) { | |
var classAttribute = root.children[i].getAttribute('class'); | |
if (classAttribute && classAttribute.toLowerCase().split(' ').indexOf(className) !== -1 /* class matched */) { | |
if (selector.length === 1) { | |
// no more selectors | |
result.push(root.children[i]); | |
} else { | |
_query(selector.slice(1), root.children[i], result); | |
} | |
} else { | |
_query(selector, root.children[i], result); | |
} | |
} | |
} else if (curSelector.charAt(0) === '#') { | |
var idName = curSelector.substr(1); | |
for (i = 0; i < root.children.length; i++) { | |
var idAttribute = root.children[i].getAttribute('id'); | |
if (idAttribute && idAttribute.toLowerCase() === idName /* id matched */) { | |
if (selector.length === 1) { | |
// no more selectors | |
result.push(root.children[i]); | |
} else { | |
_query(selector.slice(1), root.children[i], result); | |
} | |
} else { | |
_query(selector, root.children[i], result); | |
} | |
} | |
} | |
} | |
return result; | |
} | |
global.query = query; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: