Search code examples
jquerydomjquery-traversing

How to find the first ancestor of an element whose sibling is particular element in jquery?


<div>
  <input type="text">
  <span id="ending_point">
     <label>
        <span>
        <input type="text" id="starting_point">
           <span>
           </span>
        </span>
    </label>
  </span>
</div>

Here i want to find the ancestor of an element(here with id:starting_point) whose previous sibling is "input".Here the answer is span with id "ending_point" because it's previous sibling is "input".How to find this?


Solution

  • You can use a combination of .parents and .filter:

    var $ep = $("#starting_point")
      .parents()
      .filter(function() {
        return $(this).prev().is("input");
      })
      .first();
    
    // NB: the parents() method return all parents, CLOSEST ONE FIRST
    
    console.log($ep);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div>
      <input type="text">
      <span id="ending_point">
        <label>
          <span>
            <input type="text" id="starting_point">
            <span></span>
          </span>
        </label>
      </span>
    </div>