First child
jQuery :first-child selector
by cent cent
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="result">
</div>
<div class="a">
<div class="b">
</div>
<div>
<div class="b">
<div>
<div class="b">
<div>
<div class="b">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScript
var l = $('.a .b:first-child').length;
var html = '<p>length of ".a .b:first-child" = '+l+'</p>';
l = $('.a').find('.b:first-child').length;
html += '<p>length of $(".a").find(".b:first-child") = '+l+'</p>';
l = $('.a').find('.b').length;
html += '<p>length of $(".a").find(".b") = '+l+'</p>';
l = findClosest('.a', '.b').length;
html += '<p>length of findClosest(".a", ".b") = '+l+'</p>';
$('.result').html(html);
/*
* Extends jQuery 'find()' in a way that if a selector contains more children
* which can be selected with the same selector only the highest parent is picked
*/
function findClosest(parent, needle){
var $n = $(parent),
$res = $n.find(needle);
$res = $res.map(function(){
if($n.has($(this).closest(needle)))
return null;
else
return this;
});
return $res;
}