jQuery API

.closest()

Contents:

.closest( selector ) Returns: jQuery

Description: Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

  • version added: 1.3.closest( selector )

    selectorA string containing a selector expression to match elements against.

  • version added: 1.4.closest( selector [, context] )

    selectorA string containing a selector expression to match elements against.

    contextA DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.

  • version added: 1.6.closest( jQuery object )

    jQuery objectA jQuery object to match elements against.

  • version added: 1.6.closest( element )

    elementAn element to match elements against.

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest() .parents()
Begins with the current element Begins with the parent element
Travels up the DOM tree until it finds a match for the supplied selector Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
The returned jQuery object contains zero or one element The returned jQuery object contains zero, one, or multiple elements
<ul id="one" class="level-1">
  <li class="item-i">I</li>
  <li id="ii" class="item-ii">II
  <ul class="level-2">
    <li class="item-a">A</li>
    <li class="item-b">B
      <ul class="level-3">
        <li class="item-1">1</li>
        <li class="item-2">2</li>
        <li class="item-3">3</li>
      </ul>
    </li>
    <li class="item-c">C</li>
  </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

Suppose we perform a search for <ul> elements starting at item A:

$('li.item-a').closest('ul')
  .css('background-color', 'red');

This will change the color of the level-2 <ul>, since it is the first encountered when traveling up the DOM tree.

Suppose we search for an <li> element instead:

$('li.item-a').closest('li')
  .css('background-color', 'red');

This will change the color of list item A. The .closest() method begins its search with the element itself before progressing up the DOM tree, and stops when item A matches the selector.

We can pass in a DOM element as the context within which to search for the closest element.

var listItemII = document.getElementById('ii');
$('li.item-a').closest('ul', listItemII)
  .css('background-color', 'red');
$('li.item-a').closest('#one', listItemII)
  .css('background-color', 'green');

This will change the color of the level-2 <ul>, because it is both the first <ul> ancestor of list item A and a descendant of list item II. It will not change the color of the level-1 <ul>, however, because it is not a descendant of list item II.

Examples:

Example: Show how event delegation can be done with closest. The closest list element toggles a yellow background when it or its descendent is clicked.

<!DOCTYPE html>
<html>
<head>
  <style>
  li { margin: 3px; padding: 3px; background: #EEEEEE; }
  li.hilight { background: yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <ul>
    <li><b>Click me!</b></li>
    <li>You can also <b>Click me!</b></li>
  </ul>
<script>
  $( document ).bind("click", function( e ) {
    $( e.target ).closest("li").toggleClass("hilight");
  });
</script>

</body>
</html>

Demo:

Example: Pass a jQuery object to closest. The closest list element toggles a yellow background when it or its descendent is clicked.

<!DOCTYPE html>
<html>
<head>
  <style>
  li { margin: 3px; padding: 3px; background: #EEEEEE; }
  li.hilight { background: yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <ul>
    <li><b>Click me!</b></li>
    <li>You can also <b>Click me!</b></li>
  </ul>
<script>
  var $listElements = $("li").css("color", "blue");
  $( document ).bind("click", function( e ) {
    $( e.target ).closest( $listElements ).toggleClass("hilight");
  });
</script>

</body>
</html>

Demo:

.closest( selectors [, context] ) Returns: Array

Description: Gets an array of all the elements and selectors matched against the current element up through the DOM tree.

  • version added: 1.4.closest( selectors [, context] )

    selectorsAn array or string containing a selector expression to match elements against (can also be a jQuery object).

    contextA DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.

This signature (only!) is deprecated as of jQuery 1.7. This method is primarily meant to be used internally or by plugin authors.

Example:

Show how event delegation can be done with closest.

<!DOCTYPE html>
<html>
<head>
  <style></style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <ul><li></li><li></li></ul>
<script>
  var close = $("li:first").closest(["ul", "body"]);
  $.each(close, function(i){
  $("li").eq(i).html( this.selector + ": " + this.elem.nodeName );
  });</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .closest() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .closest()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Anonymous

    Best enhancement to jQuery!

    This is extremely useful as I have encountered many instances where simply finding the parent() element is insufficient.

    Previously doing a $(‘.obj’).parent().parent().find(“ul”) can be replaced by a $(‘obj’).closest(‘ul’);

    Thank you!

  • http://dazonic.myid.net/ Daz

    I agree, my favourite too. This was in the last version of jQuery by the way, I bet you’re kicking yourself for not knowing :)

  • Bob

    Can it be replaced in all instances? As the documentation shows, .closest() returns one element, while .find() returns all elements that were found. So if you wanted instead to get all the ul which are children of the obj’s parents, with closest you will only get one of those children.

  • Anonymous

    Yes, very useful. jQuery traversing tools are mostly targeted “inwards” and this is must have for getting parent DIV info without too much hassle. Here’s getting surrounding DIV’s ID when you click an item (deep) inside it:

    jQuery(‘#someitem’).click(function(){
    parent_id = jQuery(this).closest(“div[class='myparentclass']“).attr(“id”);
    });

  • http://twitter.com/tomwillmot Tom Willmot

    Worth mentioning that you can use multiple selectors ie.

    jQuery( this ).closest( 'p, tr' );

    This will return whichever element it finds first as it traverses upwards

  • http://openid-provider.appspot.com/[email protected] Guffa

    The term “up through the tree” should be avoided, as it’s not used correctly. The method is actually traversing DOWN the tree. This confusion is common, as a tree is not a very accurate analogy for a hierarchy. (All real trees that I have seen (that has not been uprooted) have their root ends downwards.)

  • stephenrs

    Sounds like you’ve never studied computer science or decision theory. The use of “tree” is a metaphor, not an analogy, and it’s generally impractical to represent a data hierarchy visually by starting with the root at the bottom (try to draw your family tree this way). Traversing “up” the tree to the root makes far more sense to people who speak the language…or whom have ever seen a family tree drawn visually.

    Please don’t confuse new users with this misinformation.

  • WaltW

    Maybe I'm misunderstanding what you're asking for, but can't you just call $.fn.parents('ul') to find all of the parents of jQuery elements matching a selector?

    $.fn.closest(sel) <=> $.fn.parents(sel + ':first')

    Isn't that right?

  • http://www.guffa.com Guffa

    A family tree works rather well as a tree, and plenty of them are drawn that way, actually with an image of a real tree as background. However, as you say, it’s impractical to represent hierarchical data with the root at the bottom, so the tree analogy (or metaphor or whatever) whould be avoided.

  • http://andir.myopenid.com/ Andir

    I'm no fan of the name: closest could refer to the children as well and it can be confusing to a casual reader.

    If you have a div outside a table and a div in one of the cells, if you want the closest div to the td it should be the child (which is one element away), not the parent(which is at least four elements away traversing up the table definition.)

  • http://twitter.com/jonashuckestein Jonas Huckestein

    Warning: closest does not work with an array of jQuery objects like follows:

    $(“.something”).closest([$(".something2"), $(".something3")])

    The reason is because internally closest() uses the elements of the passed array as object keys and they overwrite one another because objects all serialize to “[object Object]“. This is not really a bug but could easily be avoided.

    A workaround for this is using add() (although it doesn't really feel efficient):

    $(“.something”).closest([$(".something2").add($(".something3"))])

  • suggesto

    How about changing the example of the li traversals to something a bit more readable like:
    - Wiliam I
    – Richard
    – Adeliza
    – Henry I
    — Matilda

    Something based on this maybe: http://en.wikipedia.org/wiki/English_monarchs_family_tree

  • Mitridates

    It does not work for me, but it does:
    var parent_id = this.parents('.myclass').attr('id');

  • Lw

    shouldbe then “thunder”
    http://rajatarora.info/diary/w…

    :)

  • Lw

    shouldbe then “thunder”
    http://rajatarora.info/diary/w…

    :)

  • Yi3artist

    That would be lightning, but I completely agree. And “travelling up the lightning” sounds much much cooler. And now that browsers and servers faster, any plant growth analogy just seems too slow…