jquery .find equivalent in javascript

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.tsx
function findDescendants(element, selector) {
  var descendants = element.querySelectorAll(selector);
  return Array.prototype.reduce.call(element.childNodes, function (matches, child) {
    return child.nodeType === Node.ELEMENT_NODE ? matches.concat(findDescendants(child, selector)) : matches;
  }, Array.prototype.slice.call(descendants));
}
346 chars
7 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.tsx
var parent = document.getElementById('parent');
var descendants = findDescendants(parent, '.selector');
104 chars
3 lines

This will return an array of all descendants of the parent node that match the .selector CSS selector.

gistlibby LogSnag