Created
October 26, 2009 17:27
-
-
Save javascripter/218835 to your computer and use it in GitHub Desktop.
This file contains 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 querySelectorAll; | |
// multiple scoped selector not supported yet. e.g. ">embed,>object" | |
(function () { | |
var toArray = function (nodes) { | |
return [].slice.call(nodes, 0); | |
}; | |
var squeezers = { | |
">": function (node) { | |
return toArray(node.children); | |
}, | |
"+": function (node) { | |
var next = node.nextElementSibling; | |
return next ? [next] : []; | |
}, | |
"~": function (node) { | |
var nodes = [], n; | |
for (n = node.nextElementSibling; n; n = n.nextElementSibling) | |
nodes.push(n); | |
return nodes; | |
} | |
}; | |
querySelectorAll = function (selector, context) { | |
var scoped = /^\s*([>+~])(.*)/; | |
var match = selector.match(scoped); // [all, type, selector] or null | |
if (match) { | |
return squeezers[match[1]](context).filter(function (node) { | |
return node.webkitMatchesSelector(match[2]); | |
}); | |
} | |
return toArray(context.querySelectorAll(selector)); | |
} | |
})(); | |
/* | |
function like(a, b) { | |
var p = a.every(function (x, i) { return x == b[i] }); | |
console.assert(p, "test failed: %s != %s", a, b); | |
} | |
like( | |
querySelectorAll("a", document.body), | |
document.body.querySelectorAll("a") | |
); | |
like( | |
querySelectorAll("+ a", document.body), | |
document.querySelectorAll("body > a") | |
); | |
like( | |
querySelectorAll("+ *", document.head), | |
document.querySelectorAll("head + *") | |
); | |
like( | |
querySelectorAll("~ *", document.head), | |
document.querySelectorAll("head ~ *") | |
); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment