0

I have a mutation observer that returns the elements added into a webpage.
I have no control at all over these elements.

I need, given these elements, to find all instances of a certain class (a selector like ".myClass") from these elements in a scope that sums up:

  • .find(".myClass") (return all elements among all children and subchildren)
  • .filter(".myClass") (search for the class among all given elements themselves)
  • .closest(".myClass") (search for the class among the parents)

The returned array should not repeat any element.

I know the elements containing the class are all in the same level, but there is absolutely no pattern for the level of the elements returned by the observer.

This is the best solution so far, but when the added nodes come from different levels, kind of mixed up, I have a lot of unnecessarily repeated elements:

addedNodes = addedNodes.filter(el => typeof el !== 'undefined');
var $addedNodes = $(addedNodes);
var $foundComments = $addedNodes.find(".myClass").addBack(".myClass");
var $foundParents = $addedNodes.closest(".myClass");

$foundComments = $.merge($foundComments, $foundParents);

Notice that .find().addBack() does part of the job. It joins find and filter. Is there any way to joint the closest together?

Daniel Möller
  • 84,878
  • 18
  • 192
  • 214
  • Can you give an example of the input (HTML) and expected output, so we have a live example to debug? I'm not immediately seeing where any repeated elements could exist, given your current code – CertainPerformance May 16 '19 at 02:47
  • 1
    The problem comes from the given "addedNodes", which I don't control. Sometimes it comes as a list with 1 - a few "containers" (which will return the targets with "find"); 2 - a few of the "targets themselves" (will return the targets with "filter"); 3 - a few of the elements that are "children of the targets" (will return the targets with "closest") – Daniel Möller May 16 '19 at 02:52
  • Ah, makes sense. Sounds like you just need to transform the jQuery object to an array, and remove duplicates – CertainPerformance May 16 '19 at 02:58
  • Oh, come on. I'm expecting a "jquery" selector or function, not a manual array cleaning, I could have done that without asking. The idea is nice to present, but locking the question? – Daniel Möller May 16 '19 at 03:22

0 Answers0