In JavaScript, you can use querySelectorAll()
method to get all the matching child nodes within a parent node. However, there is no built-in method to recursively find all the descendants of a parent node. To achieve this functionality, you can use a recursive function like below:
index.tsx346 chars7 lines
Here, findDescendants()
function takes two arguments: the element
which is the parent node whose descendants we want to find, and selector
which is a CSS selector to match against each descendant. The function first finds all the matching descendants using querySelectorAll()
, and then uses Array.prototype.reduce()
method to iterate over all child nodes of the parent. For each child that is an element node, it recursively calls findDescendants()
on it and concatenates the returned array with the matches
array. Finally, it returns the array of all matching descendants.
You can use this function like:
index.tsx104 chars3 lines
This will return an array of all descendants of the parent
node that match the .selector
CSS selector.
gistlibby LogSnag