Definition and Usage
Closest () method returns a first ancestor element selected element.
Ancestors father, grandfather, great-grandfather, and so on.
DOM tree: This method traverse up from the current element until all the path of the document root element (), to find the first ancestor element DOM element.
This method Parents () Similarly, the DOM tree is traversed upwards, it is different:
closest()
Starting from the current element
The first single ancestor DOM tree traversal upward direction, and returns the matching expressions passed
Returns jQuery object contains zero or one element
parents()
Start from the parent element
DOM tree traversal upward direction, and returns the passed expression matches all ancestors
Returns jQuery object contains zero, one or more elements of
grammar
Returns the first ancestor element of the selected element:
$(selector).closest(filter)
Returns the first ancestor element DOM context to find the DOM tree:
$(selector).closest(filter,context)
parameter
parameter | Necessary | description |
---|---|---|
filter | Yes | Refine provisions ancestor elements range selector expression element or jQuery object. |
context | no | You can find DOM elements matching elements within it. |
Examples
The following example demonstrates return <span> first ancestor element is a <ul> element:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>欢迎来到jq教程</title> <style> .ancestors *{ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> //此版本是百度cdn 1.11.1,当然你可以使用更高的版本,从2.0版本以上的是不支持ie6-8的 <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function () { $("span").closest("ul").css({"color":"red","border":"2px solid red"}); }); </script> </head> <body> body (曾曾祖先节点) <div style="width:500px;">div (曾祖先节点) <ul>ul (第二祖先 - 第二祖先节点) <ul>ul (第一祖先 - 第一祖先节点) <li>li (直接父节点) <span>span </span> </li> </ul> </ul> </div> </body> </html>
相关方法
parent() - 返回被选元素的直接父元素
parentsUntil() - 返回两个给定参数之间的所有祖先元素