Latest web development tutorials

jQuery closest () method

jQuery traversal methods jQuery traversal methods

Examples

Back <span> first ancestor element is a <ul> element:

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

result:

body (great-great-grandparent)
div (great-grandparent)
    ul (second ancestor - second grandparent)
      ul (first ancestor - first grandparent)
    • li (direct parent) span

try it"

Definition and Usage

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

Ancestors father, grandfather, great-grandfather, and so on.

DOM tree: This method traverses up from the current element until all the path of the document root element (<html>), to find the first ancestor element DOM element.

This method parents () is similar, both traverse up the DOM tree, the difference is:

closest ()

  • Starting from the current element
  • The first single ancestor traversal along the DOM tree upwards, and returns the matching expression passed
  • Returns zero or one element of jQuery object

parents ()

  • Starting from the parent element
  • Along the DOM tree traversal up and returns expression matches all ancestors passed
  • Returns zero, one or more elements of the jQuery object

Other related methods:

  • parent () - Returns the direct parent element of the selected element
  • parentsUntil () - Returns all ancestors of the element parameters between the two to

grammar

Returns selected elements of the first ancestor element:

$(selector).closest( filter )

Returns DOM tree DOM context find the first ancestor element:

$(selector).closest( filter,context )

参数 描述
filter 必需。规定缩小搜索祖先元素范围的选择器表达式、元素或 jQuery 对象。
context 可选。在其内可以找到匹配元素的 DOM 元素。

Examples

More examples

Back <span> first ancestor element is a <span> element
Because this method from the beginning of the current element, search <span> first <span>, will return to <span>.

In the DOM element as the context is passed to the first ancestor search
Two parameters are used in the DOM element is passed as a context to search for the first <ul> element.


jQuery traversal methods jQuery traversal methods