closest

UK [k'ləʊsɪst] US [k'loʊsɪst]

adj.The closest

jquery closest() method syntax

Function: closest() method obtains the first ancestor element matching the selector, starting from the current element and going up the DOM tree.

Syntax: .closest(selector)

Parameters:

ParameterDescription
selector String value, containing the selector expression of the matching element.

Description: Given a jQuery object that represents a collection of DOM elements, the .closest() method allows us to retrieve these elements in the DOM tree and their ancestor element and constructs a new jQuery object with the matching element. The .parents() and .closest() methods are similar in that they both traverse up the DOM tree.

jquery closest() method example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></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>
<script>
  $( document ).bind("click", function( e ) {
    $( e.target ).closest("li").toggleClass("hilight");
  });
</script>
</body>
</html>
Run instance »

Click the "Run instance" button to view the online instance