Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active May 6, 2024 04:59
Show Gist options
  • 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