Skip to content

Instantly share code, notes, and snippets.

@myurasov
Created July 31, 2015 09:18
Show Gist options
  • Save myurasov/99761a62b2c5ba0c9aba to your computer and use it in GitHub Desktop.
Save myurasov/99761a62b2c5ba0c9aba to your computer and use it in GitHub Desktop.
Simpe element querying by class/id
(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);
@myurasov
Copy link
Author

Usage:

query(".class1");
query("#id1 .class2")
query(".class1 .class2 #id1")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment