Skip to content Skip to sidebar Skip to footer

Can Jquery.find() Select Only Direct Children?

What argument should I provide to jQuery.find() to select the elements children and no other elements? I can't lead the selector with '>' and having '*' will select all descenda

Solution 1:

Start your selector with > as you mentioned in your question. Try it:

var s = ".classA",
    n = $('#wrapper').find('>'+s).length;

alert('Found '+ n +' direct children of #wrapper with the "'+ s +'" selector.'); // 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="wrapper">
    <div class="classA"></div>     <!-- Selected -->
    <div class="classA">           <!-- Selected -->
        <div class="classA"></div> <!-- Ignored -->
    </div>
    <div class="classC">
        <div class="classA"></div> <!-- Ignored -->
    </div>
    <div class="classB">
        <div class="classB"></div>
    </div>
    <div class="classA"></div>     <!-- Selected -->
</div>

Or use $.children(), as you mentioned it in your question:

var s = ".classA",
    n = $('#wrapper').children(s).length;

alert('Found '+ n +' direct children of #wrapper with the "'+ s +'" selector.'); // 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="wrapper">
    <div class="classA"></div>     <!-- Selected -->
    <div class="classA">           <!-- Selected -->
        <div class="classA"></div> <!-- Ignored -->
    </div>
    <div class="classC">
        <div class="classA"></div> <!-- Ignored -->
    </div>
    <div class="classB">
        <div class="classB"></div>
    </div>
    <div class="classA"></div>     <!-- Selected -->
</div>

Solution 2:

I am aware of jQuery.children(), but this is for a library so the user is able to provide their own selector

But JQuery's .children() receives a selector as parameter:

.children( [selector ] )
Description: Get the children of each element in the set of matched elements, optionally filtered by a selector.

https://api.jquery.com/children/


Solution 3:

Use Immediate Child Elements with > this is the code you need:

elemnt.find("> selector");

That should do the trick.


Post a Comment for "Can Jquery.find() Select Only Direct Children?"