Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 586
static Avatar asked Mar 24 '23 18:03

static


1 Answers

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

like image 185
static Avatar answered Apr 09 '23 18:04

static