When I have a class that matches several elements is there a way to process each tier of parents inidividually
$(".myWidespreadClass").parents() // [immediateParent1, immediateParent2, deeperAncestor1, deeperAncestor2]
I would like to be able to run something like .each() but where the first iteration runs over immediate parents, the second over deeper ancestors at the next level etc…
Fascinating question. I think you’ll want a loop, something like this:
Live example | Live source – Update but see below, that could terminate early
You may want to terminate a bit earlier than that, e.g.:…depending on your needs. I did in the example. See below.
Update Actually, you have to be careful with the early termination, probably better off filtering when you’re processing the parents instead, something like this:
Live example | Live source
The reason being that your initial set of elements may be at wildly different levels in the DOM, and so you’ll reach the topmost element for some of them sooner than for others. The
bodycheck above may not be appropriate for your needs, but you get the idea.