In jQuery you can call closest
to find the closest parent.
If I have a a
in a li
in a ul
in a td
in a table
. I want to find out if the ul
parent is closer than the table
parent. Obviously in this case the answer is obvious.
If I run $('a').closest('table').length
or $('a').closest('ul').length
both return 1.
I would like to find out which parent is closer in the DOM.
Technically if there were a method than in this case $('a').closer('ul', 'table')
would return the ul
because it is closer in the DOM.
<table> <!-- Is this closer -->
<tr>
<td>
<ul> <!-- Or is this closer -->
<li>
<a href="#">A button</a>
</li>
</ul>
</td>
</tr>
</table>
You can list multiple element selectors to the closest
function, it will only find the closest of one of them:
$('a').closest('table, ul')
Example:
$(document).on("click", function( event ) {
$(event.target).closest("li, b").toggleClass("hilight");
});
.hilight{
background: rgba(255, 0, 0, 0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><b>Click me!</b></li>
<li>You can also click this line <b>or click me!</b></li>
</ul>
Use .parents()
. It returns a list of all parents that are ordered from closest to farthest.
The difference between using this and using .closest(selector)
is that it accepts a jQuery object instead of a selector string, which has to be hard coded. Meanwhile jQuery objects can be collections and so can be generated on the fly.
(function($) {
$.fn.getClosest = function(testElements) {
var element = $(this);
var parents = element.parents();
var indexClosest = Number.MAX_VALUE;
testElements.each(function() {
var index = parents.index($(this));
if (index > -1 && index < indexClosest)
indexClosest = index;
});
return parents.eq(indexClosest);
};
})(jQuery);
Use the function like this:
$("a").getClosest($("table, ul"))
Fiddle with advanced use case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With