Last active
June 7, 2023 17:09
-
-
Save moimikey/6a591b0a77afd6c2062aab43a67fe876 to your computer and use it in GitHub Desktop.
Traverse the DOM with cascading predicates
This file contains hidden or 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
function traverseDOMNodes(node, predicates, cb) { | |
if (predicates.length === 0) { | |
// Base case: If there are no more predicates, invoke the callback. | |
return cb(node); | |
} | |
const [currentPredicate, ...remainingPredicates] = predicates; | |
const children = node.childNodes; | |
for (let child of children) { | |
if (currentPredicate(child)) { | |
const result = traverseDOMNodes(child, remainingPredicates, cb); | |
if (result) { | |
return result; | |
} | |
} | |
} | |
return null; | |
} | |
// Ex. Only nodes that exact match UL > LI > DIV > SPAN | |
const predicates = [ | |
node => node.nodeName === 'UL', | |
node => node.nodeName === 'LI', | |
node => node.nodeName === 'DIV', | |
node => node.nodeName === 'SPAN' | |
]; | |
traverseDOMNodes(document.body, predicates, (result) => { | |
console.log(result); | |
// You can map over this. perhaps grab attributes. | |
// | |
// result.map(x => x.attributes.value.nodeValue); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment