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