4

Assume an html document:

<html>
  <head>
  </head>
  <body>
    <li id="eee">
      <li>aaa</li>
      <span>bbb</span>
        ...
          <div>
            <button id="ccc">ddd</button>
          </div>
        ...
    </li>
  </body>
</html>

Using $('#ccc').closest('li') jQuery will select the <li id="eee">...</li> - the nearest ancestor of the <button id="ccc">. Is it possible to select <li>aaa</li> as "really" closest <li> element to the <button id="ccc"> (so, it need not be an ancestor, but enough be a sibling of one of the ancestors)?

Update:

valid html (specially for @PSL guy, already deleted his comments):

<html>
  <head>
  </head>
  <body>
    <div id="eee">
      <div>aaa</div>
      <span>bbb</span>
      <ul>
        <li>fff</li>
        <li>
          <button id="ccc">ddd</button>
        </li>
      </ul>
    </li>
  </body>
</html>

how to get the <div>aaa</div> without using the parent() function, but using smth. like trueClosest('div') taking siblings, ancestors and siblings of the ancestors in account?

I just want to know, if jQuery has such a function or not?

static
  • 8,126
  • 15
  • 63
  • 89
  • ok, it is invalid, but chrome still can perform on it, so it is possible to understand what I mean. The question is conceptual: is it possible to select not the direct nearest ancestor (father, (grand)father) but a sibling of any ancestor (uncle, brother of (grand)father), that match an expression (e.g. `closest(expression)`) – static Jun 01 '13 at 04:35
  • specially for @PSL a VALID html in update of the question, if it is not clear form the original, what and how I want to select and what and how I don't want. – static Jun 01 '13 at 04:49

2 Answers2

7

One could use the following:

$('#startingElement').closest(':has(#desiredElement)').children('#desiredElement')

So: find the closest element to the #startingElement which has a #desiredElement and then get it(them) through children(function);

static
  • 8,126
  • 15
  • 63
  • 89
0

Does this help?
I often use this method when traversing the DOM for parents/siblings

$(this).parent().parent().find('#something')
Charlie Walton
  • 312
  • 5
  • 16