Created
September 30, 2014 06:37
-
-
Save KrisSiegel/1824261b7da41adafe17 to your computer and use it in GitHub Desktop.
:eq() selector implementation for native JavaScript's querySelectorAll
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
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