Home  >  Article  >  Web Front-end  >  Example of usage of closest() function in jQuery_jquery

Example of usage of closest() function in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:21:501416browse

The example in this article describes the usage of closest() function in jQuery. Share it with everyone for your reference. The specific analysis is as follows:

This function starts from the element itself, matches the upper elements step by step, and returns the first matching element.
The 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.

Grammar structure 1:

Copy code The code is as follows:
$(selector).closest(expr, context)

Parameter list:

参数 描述
expr 用以过滤元素的表达式
context 可选。作为待查找的 DOM 元素集或者文档。

Example code:

Example 1:

Copy code The code is as follows:






closest() function-Script Home





I am div

I am grandson p



I am my sonp



I am a brotherp




Example 2:

Copy code The code is as follows:






closest() function-Script Home






I am grandson p



I am my sonp



I am a brotherp




Since the div with the id of father is not within the div with the id of children, its border cannot be set to red.

Grammar structure 2:

Copy code The code is as follows:
$(selector).closest(element)

Parameter list:

参数 描述
element 用于匹配元素的DOM元素或者jQuery元素。

Example code:

Example 1:

Copy code The code is as follows:






closest() function-Script Home






I am grandson p



I am my sonp



I am a brotherp




Example 2:

Copy code The code is as follows:






closest() function-Script Home






I am grandson p



I am my sonp



I am a brotherp




I hope this article will be helpful to everyone’s jQuery programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn