YouTip LogoYouTip

Traversing Closest

# jQuery closest() Method [![Image 4: jQuery Traversing Methods](#) jQuery Traversing Methods](#) ## Example Return the first ancestor element of the `` element, which is a `
    ` element: ```javascript $(document).ready(function(){ $("span").closest("ul").css({"color":"red","border":"2px solid red"}); }); [Try it Yourself Β»](#) * * * ## Definition and Usage The `closest()` method returns the first ancestor element of the selected element. Ancestors are parent, grandparent, great-grandparent, and so on. **DOM Tree:** The method traverses up the DOM tree from the current element towards the document root (``) to find the first ancestor element. This method is similar to [parents()](#), as both traverse up the DOM tree. The difference is: **_closest()_** * Starts from the current element * Traverses up the DOM tree and returns the first single ancestor that matches the passed expression * Returns a jQuery object containing zero or one element **_parents()_** * Starts from the parent element * Traverses up the DOM tree and returns all ancestors that match the passed expression * Returns a jQuery object containing zero, one, or multiple elements **Other Related Methods:** - Returns the direct parent element of the selected element - Returns all ancestor elements between two given arguments * * * ## Syntax Return the first ancestor element of the selected element: ```javascript $(selector).closest(filter) Return the first ancestor element in the DOM tree, found using a DOM context: ```javascript $(selector).closest(filter, context) | Parameter | Description | | :--- | :--- | | _filter_ | Required. Specifies a selector expression, element, or jQuery object to narrow the search for ancestor elements. | | _context_ | Optional. A DOM element within which to find matching elements. | ![Image 5: Example](#) ## More Examples [Return the first ancestor element of the `` element, which is a `` element](#) Since the method starts from the current element, searching for the first `` of the `` will return the `` itself. (#) Using two parameters to pass a DOM element as context to search for the first `
      ` element. * * jQuery Traversing Methods](#)
← Traversing PrevTraversing Children β†’