Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find which parent is closer?

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>
like image 304
Johnston Avatar asked Dec 18 '22 19:12

Johnston


2 Answers

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>
like image 167
Fabian Horlacher Avatar answered Jan 02 '23 22:01

Fabian Horlacher


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

like image 21
4castle Avatar answered Jan 02 '23 21:01

4castle