0
<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?

madalinivascu
  • 32,064
  • 4
  • 39
  • 55

3 Answers3

0

Here is my solution:

  $("input + span").first();

This is your selector: $("input + span"). It selects all spans they are following immidiatly after an input. And with .first() you select the first one.

I created a JSFiddle for you.

And here is the Selectors Reference

Greetz Eldo.ob

Eldo.Ob
  • 774
  • 4
  • 16
0

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>
Salman A
  • 262,204
  • 82
  • 430
  • 521
0

If you know the hierarchy exactly beforehand, then I'd use

$( "#starting_point" ).parent().parent().parent().parent().find( "#ending_point" );

or do something with .parentsUntil() (https://api.jquery.com/parentsUntil/). (OK, not a beautiful solution, but surely works.)

If you do not know the hierarchy (it's created dynamically), but you are sure, that #starting_point is "lower" than #ending_point, then you may create a recursive function for that, checking every level for the type you are looking for.

// start_obj is the jQuery object you start your recursive function from
// end_type is the type of element you are looking for in the hierarchy (e.g. input[ type="text" ] in your case

function get_sibling_on_other_level( start_obj, end_type ) {
    var grampy = start_obj.parent().parent();
    if ( grampy.find( end_type ).length > 0 ) {
        return grampy.children( end_type );
    } else {
        // start the iteration "one level higher"
        // actually you should stop at "body" level - if you did not find
        // what you were looking for, then it's not in that branch of hierarchy
        get_sibling_on_other_level( start_obj.parent(), end_type );
    }
}

Other jQuery method used in the function: https://api.jquery.com/children/

muka.gergely
  • 8,063
  • 2
  • 17
  • 34