Home > Article > Web Front-end > How to use closest method in jquery
In jquery, the closest method is used to return the first ancestor element of the selected element; this function can match upwards starting from the element itself, and return the first matched element. If no match is found, Returns an empty jQuery object with the syntax "element object.closest(selector expression matching the element)".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
closest() method returns the first ancestor element of the selected element.
Ancestors are father, grandfather, great-grandfather, and so on.
Starting from the current element, traverse up the DOM tree and return the first single ancestor that matches the passed expression, returning a jQuery object containing zero or one element
closest( ) function will first check whether the current element matches, and if it matches, it will directly return the element itself. If there is no match, search upwards for the parent element, layer by layer, until an element matching the selector is found. If nothing is found, an empty jQuery object is returned.
The syntax is:
Return the first ancestor element of the selected element:
$(selector).closest(filter)
Return the first ancestor element in the DOM tree searched using DOM context:
$(selector).closest(filter,context)
filter Required. Specifies a selector expression, element, or jQuery object that narrows the search for ancestor elements.
context Optional. The DOM element within which the matching element can be found.
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> .ancestors *{ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("span").closest("ul").css({"color":"red","border":"2px solid red"}); }); </script> </head> <body class="ancestors">body (曾曾祖先节点) <div style="width:500px;">div (曾祖先节点) <ul>ul (第二祖先 - 第二祖先节点) <ul>ul (第一祖先 - 第一祖先节点) <li>li (直接父节点) <span>span</span> </li> </ul> </ul> </div> </body> <!-- 在这个例子中, $("span").closest("ul") 指我们查找一个span元素的第一个ul祖先。最靠近span的祖先是li,但是由于查到一个div,jQuery 跳过li元素继续查找下一个祖先,直到它找出我们要查找的ul.假如我们用parents() 方法替代,它将返回ul的祖先 。 --> </html>
Output result:
Related video tutorial recommendation: jQuery video tutorial
The above is the detailed content of How to use closest method in jquery. For more information, please follow other related articles on the PHP Chinese website!