JQuery find which parent is closer?

In jQuery, you can call closestto find the closest parent.

If I have ain liin ulin tdin table. I want to find out if a parent is closer ulthan a parent table. Obviously, in this case the answer is obvious.

If I run $('a').closest('table').lengthor $('a').closest('ul').length, return 1.

I would like to know which parent is closer in the DOM.

Technically, if there was a method that in this case $('a').closer('ul', 'table')would return ul, because it is closer to the DOM.

<table> <!-- Is this closer -->
    <tr>
        <td>
            <ul> <!-- Or is this closer -->
                <li>
                    <a href="#">A button</a>
                </li>
            </ul>
        </td>
    </tr>
</table>
+4
source share
5 answers

closest, :

$('a').closest('table, ul')

:

$(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>
Hide result
+5

; :

var $parentsUntilTable = $('li').parentsUntil('table');
var $parentsUntilUl = $('li').parentsUntil('ul');
console.log($parentsUntilTable.length < $parentsUntilUl.length
           ? 'table is closer'
           : 'ul is closer');
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.imtqy.com/stack-snippet-console/console.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>
      <ul>
        <li>
        </li>
      </ul>
    </td>
  </tr>
</table>
Hide result
+2

.parents(). , .

.closest(selector) , jQuery , . jQuery .

(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);

:

$("a").getClosest($("table, ul"))

+2

.closer(), , :

$.fn.closer = function(varargs) {
  var $elem = $(this);
  while ($elem.length) {
    for (var i = 0, len = arguments.length; i < len; i++) {
      if ($elem.is(arguments[i])) {
        return arguments[i];
      }
    }
    $elem = $elem.parent();
  }
  return null;
};

jsFiddle.

+1

node, -.

: fooobar.com/questions/237358/... -

$(elem1).offset().top - $(elem2).offset.().top

, DOM - .

, 0, elem2 , elem1 .

-1

All Articles