Skip to content

Instantly share code, notes, and snippets.

@jpiccari
Last active August 29, 2015 14:03
Show Gist options
  • Save jpiccari/ce546178887a02194f40 to your computer and use it in GitHub Desktop.
Save jpiccari/ce546178887a02194f40 to your computer and use it in GitHub Desktop.
Quick demo of how a JavaScript based selector engine might work.
function select(selector) {
var elements = [document],
queryStart = 0,
callQueue = [],
temp,
i;
for (i = 0; i < selector.length; i++) {
switch (selector[i]) {
case '#':
queryStart = i + 1;
method = 'getElementById';
break;
case '.':
queryStart = i + 1;
method = 'getElementsByClassName';
break;
case ' ':
callQueue.push({
method: method,
argument: selector.substring(queryStart, i)
});
queryStart = i + 1;
break;
}
}
callQueue.push({
method: method,
argument: selector.substring(queryStart, i)
});
while (callQueue.length) {
temp = callQueue.shift();
for (i = elements.length - 1; i >= 0; i--) {
temp = elements.shift()[temp.method](temp.argument);
elements.push.apply(elements, temp instanceof HTMLCollection ? temp : [temp]);
}
}
return elements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment