tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

closest()

Contents:

.closest( selector )

Returns: jQuery

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

.closest( selector )

version added: 1.3
selector

A string containing a selector expression to match additional elements against.

.closest( selector, [ context ] )

version added: 1.4
selector

A string containing a selector expression to match additional elements against.

context

A 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.

.closest( jQuery object )

version added: 1.6
jQuery object

A jQuery object to match elements against.

.closest( element )

version added: 1.6
element

An element to match elements against.

Given a jQuery object that represents a set of DOM elements, the .closest() method allows us to search through these elements and their ancestors in the DOM tree and construct 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.

Example

Show how event delegation can be done with closest.
    $(document).bind("click", function (e) {
      $(e.target).closest("li").toggleClass("hilight");
    });


The output of the code above will be:

Example - Full source:

<!DOCTYPE html>

<html>

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script type="text/javascript" language="javascript">

  $(document).ready(function(){
    
    $(document).bind("click", function (e) {
      $(e.target).closest("li").toggleClass("hilight");
    });

  });
  </script>

  <style>
  li { margin: 3px; padding: 3px; background: #EEEEEE; }
  li.hilight { background: yellow; }
  </style>

</head>
<body>
  <ul>
<li><b>Click me!</b></li>

<li>You can also <b>Click me!</b></li>

</ul>
</body>
</html>

Example 2

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>
The output of the code above will be:

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

.closest( selector, [ context ] )

version added: 1.4
selector

A string containing a selector expression to match additional elements against.

context

A 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 method is primarily meant to be used internally or by plugin authors.

Example

Show how event delegation can be done with closest.
var close = $("li:first").closest(["ul", "body"]);
  $.each(close, function(i){
  $("li").eq(i).html( this.selector + ": " + this.elem.nodeName );
});
The output of the code above will be:

Example - Full source:

Show how event delegation can be done with closest.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" language="javascript">
  $(document).ready(function(){
   var close = $("li:first").closest(["ul", "body"]);
  $.each(close, function(i){
  $("li").eq(i).html( this.selector + ": " + this.elem.nodeName );
});
  });
  </script>
</head>
<body>
	<ul><li></li><li></li></ul>
</body>

</html>
Was this information helpful?
   

Comments