static
static

Reputation: 8386

How select a closest element (must not be a parent of this) using jQuery?

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?

Upvotes: 4

Views: 3753

Answers (2)

static
static

Reputation: 8386

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);

Upvotes: 7

Charlie Walton
Charlie Walton

Reputation: 312

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

$(this).parent().parent().find('#something')

Upvotes: 0

Related Questions