Is there a function similar to jQuery
.closest()
but for traversing descendants and returning only closest ones?
I know that there is
In case someone's looking for a pure JS solution (using ES6 instead of jQuery), here's the one I use:
Element.prototype.QuerySelector_BreadthFirst = function(selector) {
let currentLayerElements = [...this.childNodes];
while (currentLayerElements.length) {
let firstMatchInLayer = currentLayerElements.find(a=>a.matches && a.matches(selector));
if (firstMatchInLayer) return firstMatchInLayer;
currentLayerElements = currentLayerElements.reduce((acc, item)=>acc.concat([...item.childNodes]), []);
}
return null;
};
You can just simply put,
$("#find-my-closest-descendant").siblings('.closest:first');
You can use find
with the :first
selector:
$('#parent').find('p:first');
The above line will find the first <p>
element in the descendants of #parent
.
you have a lot of options, however $("#parent").children(".child");
is the fastet.
check this article for details and benchmark
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?
I would use the following to include the target itself if it matches the selector:
var jTarget = $("#doo");
var sel = '.pou';
var jDom = jTarget.find(sel).addBack(sel).first();
Markup:
<div id="doo" class="pou">
poo
<div class="foo">foo</div>
<div class="pou">pooo</div>
</div>