0

I am looking for jQuery slector that will find all descendants of passed jQuery object that are not nested in any element that fits same selector. Consider following HTML:

<body>
    <div class="container" id="1">
        <div class="container" id="11"></div>
        <div class="container" id="12"></div>
    </div>

    <div class="container" id="2"></div>

    <div class="noncontainer">
        <div class="container" id="3">
            <div class="container" id="31"></div>
        </div>
    </div>
</body>

In this example $("body").find(".container magicSelector") should return divs 1, 2 and 3. $("#1").find(".container magicSelector") should return divs 11 and 12.

EDIT: I have wrote a function for that here, but I think that selector would be cleaner and faster.

Ondra Netočný
  • 410
  • 3
  • 16

1 Answers1

1

Use not() for first case

$("body").find(".container").not('.container .container');

And for second use descendent in the selector

$("body").find('.container .container');
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 2
    I need general selector for all cases, not just for this particular example. Search for all descendants with .container class and exclude those that are not the first (.container) in line between them and root element. – Ondra Netočný Jul 13 '16 at 18:30
  • I have wrote a [function](https://jsfiddle.net/netaques/sc72fq1x/) which does the job, but selector would be better. – Ondra Netočný Jul 13 '16 at 18:38
  • Haven't shown why what I gave you won't work. Your function isn't doing same as what was asked in question – charlietfl Jul 13 '16 at 18:40
  • Your solution would work just for my particular example. In other cases (different html markup, different root elemnt etc.), your selectors would fail. – Ondra Netočný Jul 13 '16 at 18:43
  • So provide more details. It does exactly what was asked with information that was given – charlietfl Jul 13 '16 at 18:43
  • Imagine complex html, that contains lots of .container divs, that are not direct descendants (there could be any number of other tag between them). I need to be able to search for all descendats of arbitrary tag from whole html document that fits my requirement (they are first nested .container of given root tag). – Ondra Netočný Jul 13 '16 at 18:48
  • Create html demo that is more representative. You might need to just wrap this code into function that passes in class and create the class selector in the function. Search criteria and use case is still vague – charlietfl Jul 13 '16 at 18:51
  • The only think I was wondering is if there is kind of selector that will do the same as function findFirstElements in provided jsfiddle. I think that this is enough to know. If you do not think so, please let it be. – Ondra Netočný Jul 13 '16 at 20:52