Last active
May 6, 2024 04:59
-
-
Save treshugart/82c1fe2dfbfdcf6cec97b3db137d4c69 to your computer and use it in GitHub Desktop.
document.reduce() - querySelectorAll() but with a callback instead of a selector
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
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