Skip to content

Instantly share code, notes, and snippets.

@javascripter
Created October 26, 2009 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javascripter/218835 to your computer and use it in GitHub Desktop.
Save javascripter/218835 to your computer and use it in GitHub Desktop.
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