Skip to content

Instantly share code, notes, and snippets.

@KrisSiegel
Created September 30, 2014 06:37
Show Gist options
  • Save KrisSiegel/1824261b7da41adafe17 to your computer and use it in GitHub Desktop.
Save KrisSiegel/1824261b7da41adafe17 to your computer and use it in GitHub Desktop.
:eq() selector implementation for native JavaScript's querySelectorAll
var querySelectorAllWithEq = function (selector) {
if (selector === undefined) {
return null;
}
var queue = [];
var process = function (input) {
if (input.indexOf(":eq(") === -1) {
return undefined;
}
var eqlLoc = input.indexOf(":eq(");
var sel = input.substring(0, eqlLoc);
var ind = input.substring((eqlLoc + 4), input.indexOf(")", eqlLoc));
selector = input.substring(input.indexOf(")", eqlLoc) + 1, input.length);
if (sel.charAt(0) === ">") {
sel = sel.substring(1, sel.length);
}
if (selector.charAt(0) === ">") {
selector = selector.substring(1, selector.length);
}
queue.push({
selector: sel,
index: ind
});
}
while (selector.indexOf(":eq") !== -1) {
process(selector);
}
var result;
while (queue.length > 0) {
var item = queue.shift();
result = (result || document).querySelectorAll(item.selector)[item.index];
}
if (selector.trim().length > 0) {
return (result || document).querySelectorAll(selector);
}
return [result];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment