Easy Tutorial
❮ Html Wrapall Html Wrapinner ❯

jQuery closest() Method

jQuery Traversing Methods

Example

Return the first ancestor element of a <span>, which is a <ul> element:

$(document).ready(function(){
    $("span").closest("ul").css({"color":"red","border":"2px solid red"});
});

Definition and Usage

The closest() method returns the first ancestor element of the selected element.

Ancestors are the parent, grandparent, great-grandparent, and so on.

DOM Tree: This method traverses upwards from the current element to the document root (<html>) to find the first ancestor element in the DOM.

This method is similar to parents(), both traversing upwards through the DOM tree, but with differences:



Other Related Methods:


Syntax

Return the first ancestor element of the selected element:

Return the first ancestor element in the DOM tree found using DOM context:

Parameter Description
filter Required. Specifies a selector expression, element, or jQuery object to narrow down the search for ancestor elements.
context Optional. A DOM element within which a matching element can be found.

More Examples

Return the first ancestor element of a <span>, which is a <span> element

Pass a DOM element as context to search for the first ancestor element


jQuery Traversing Methods

❮ Html Wrapall Html Wrapinner ❯