Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active June 7, 2023 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/6a591b0a77afd6c2062aab43a67fe876 to your computer and use it in GitHub Desktop.
Save moimikey/6a591b0a77afd6c2062aab43a67fe876 to your computer and use it in GitHub Desktop.
Traverse the DOM with cascading predicates
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