JQuery find closest item

Is there a jQuery function that combines the upside of closest() or parents() and the children() function down?

For instance:

 <span id="container"> <div class="a 1"></div> <div class="b 2"></div> <div class="c 3"> <div class="d 4"></div> <div class="b 5"></div> </div> <span> 

$(".c").something(".b"); should return the element "nearest" .b or .2

+4
source share
1 answer

I made a small closestDesc plugin for this.

 (function( $ ) { $.fn.closestDesc = function(selector) { var selection = []; var query = function () { this.children().each(function() { if ($(this).is(selector)) { selection.push(this); } else { query.call(this); } }); }; query.call(this); return this.pushStack(selection, "closestDesc", selector); }; })(jQuery); 

This captures all the closest descendants matching the selector.

Fiddle: http://jsfiddle.net/uGR2a/9/

+1
source

Source: https://habr.com/ru/post/1495406/


All Articles