Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active September 22, 2016 04:03
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 treshugart/82c1fe2dfbfdcf6cec97b3db137d4c69 to your computer and use it in GitHub Desktop.
Save treshugart/82c1fe2dfbfdcf6cec97b3db137d4c69 to your computer and use it in GitHub Desktop.
document.reduce() - querySelectorAll() but with a callback instead of a selector
document.reduce = Element.prototype.reduce = function(cb) {
const filter = node => cb(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
// Old IE requires a function other browsers require { acceptNode }.
filter.acceptNode = filter;
// Old IE requires the last parameter.
const walker = document.createTreeWalker(this, NodeFilter.SHOW_ELEMENT, null, false);
const nodels = [];
while (walker.nextNode()) {
const { currentNode } = walker;
if (cb(currentNode)) {
nodels.push(currentNode);
}
}
return nodels;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment