4

I am trying to use the jquery closest command to find a particular element based on if the element has a particular sibling. I have been playing with different selectors but haven't been able to find one yet that does what I want.

So for example, if the structure was something like the following

<div>
    <table>
        <tr>
            <td>
                  <span a>cell 1</span>
                  <span>cell 2</span>
            </td>
            <td siblingmatch="true">
                  <span b>cell 1</span>
                  <span>cell 2</span>
            </td>
        </tr>
    </table>

    <span siblingmatch="true">test 1</span>
</div>

If I ran closest starting from the span marked with a, I would want it to return it's parent td since it has a sibling marked with the siblingmatch attribute. However, if I ran the same command starting from the span marked with b, I would want it to return the table tag since this is the first parent it finds with a sibling marked with the siblingmatch attribute.

bbeaudet
  • 43
  • 2

1 Answers1

3

You can use parents and filter methods.

$('span').click(function(){
    var matched = $(this).parents().filter(function(){
         return $(this).siblings('[siblingmatch]').length;
    }).first();
});

http://jsfiddle.net/WW5qL/

Note that siblingmatch is not a valid attribute, you can use HTML5 data-* attributes instead.

Ram
  • 143,282
  • 16
  • 168
  • 197
  • Yes, siblingmatch wasn't the actual attribute name, just something for this example. I ran your example and that does seem to return what I want. I noticed you are not using the closest() function in your code, instead the parents filter. Is there a reason to use one vs another and could I do the same thing with closest()? – bbeaudet Mar 18 '13 at 20:12
  • Responding to my own comment: closest() doesn't support a function, so that would require a selector, which is where I was struggling. The parents().filter() allows a function, so that provides a little more flexibility. – bbeaudet Mar 18 '13 at 20:28
  • 1
    @bbeaudet `closest` only returns matching parent element (_specified by the selector_), it's not a useful method to be used here vs `parents` returns all the parent elements of the selected element (_most of the times I do not use this function_) which allows filtering them. Note that both of the functions do not accept `function`, using `filter` is a chainability that jQuery provides. – Ram Mar 18 '13 at 20:35