4

Is there a jQuery function that combines the upward-looking closest() or parents() and the downward looking children() function?

For example:

<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 'closest' .b element, or .2

d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • I'm not aware of one. You could chain a few together however, to get this effect `$('.c').parent().children('.b');` – War10ck Aug 05 '13 at 20:54
  • 1
    How would you differentiate between .b if .d was .b instead? you'd have two elements that are the same distance from each other, one in either direction. – Kevin B Aug 05 '13 at 20:55
  • 5
    what youre talking about is a matter of perspective. I would consider the child element closer to .c as it resides with in it. – Rooster Aug 05 '13 at 20:56
  • Do you have an order of operations? In other words, if the selectors were the "same distance" from `.c`, which would you want returned? – adamdehaven Aug 05 '13 at 20:57
  • 2
    Clearly it doesn't exist because it would be difficult to decide what would be considered closest in the many different situations that can arise, leading to a method that is confusing/hard to understand. – Kevin B Aug 05 '13 at 20:58
  • Totally agree with all of you - thanks... i forgot to include that... So is it safe to say this doesn't exist and it's one or the other (or a combination)? – d-_-b Aug 05 '13 at 21:00
  • 1
    You can write your own function, depending on the order of operations. You need to decide if parent(), sibling(), or child() takes precedence (and in what order) – zethus Aug 05 '13 at 22:29

1 Answers1

1

I made sometime a little 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 catches all closest descendants, matching the selector.

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

metadings
  • 3,798
  • 2
  • 28
  • 37