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?