Similar to jQuery .closest() but traversing descendants?
Is there a function similar to jQuery
.closest()
but for traversing descendants and returning only closest ones?
I know that there is .find()
function, but it returns all possible matches, not closest.
Edit:
Here is definition of closest (at least for me):
In first place all childrens are traversed, then each individuals childrens are traversed.
In example given below id='2'
is closest .closest
descendants of id="find-my-closest-descendant"
<div id="find-my-closest-descendant">
<div>
<div class="closest" Id='1'></div>
</div>
<div class="closest" Id='2'></div>
</div>
Please see JSfiddle link.
If by "closest" descendant you mean the first child then you can do:
$('#foo').find(':first');
Or:
$('#foo').children().first();
Or, to look for the first occurrence of a specific element, you could do:
$('#foo').find('.whatever').first();
Or:
$('#foo').find('.whatever:first');
Really though, we need a solid definition of what "closest descendant" means.
E.g.
<div id="foo">
<p>
<span></span>
</p>
<span></span>
</div>
Which <span>
would $('#foo').closestDescendent('span')
return?
According to your definition of closest
, I've written the following plugin:
(function($) {
$.fn.closest_descendent = function(filter) {
var $found = $(),
$currentSet = this; // Current place
while ($currentSet.length) {
$found = $currentSet.filter(filter);
if ($found.length) break; // At least one match: break loop
// Get all children of the current set
$currentSet = $currentSet.children();
}
return $found.first(); // Return first match of the collection
}
})(jQuery);