Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the closest method in jquery

Shulou Source: shulou.com Published: 2022-05-31 18:05:27 10月04日 Update

This article introduces the relevant knowledge of "how to use the closest method in jquery". In the operation process of actual cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

In jQuery, the closest method returns the first ancestor element of the selected element; this function can match up from the element itself and return the first matching element, if there is no match, return an empty jQuery object, syntax is "element object.closest(selector expression matching element)".

Operating environment for this tutorial: Windows 10 system, jquery version 3.2.1, Dell G3 computer.

How to use the closest method in jquery

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

Ancestors are fathers, grandfathers, great-grandfathers, and so on.

Travels up the DOM tree from the current element and returns the first single ancestor matching the passed expression, returning a jQuery object with zero or one element

The closest() function first checks whether the current element matches, and if so returns the element itself. If there is no match, look up the parent element, level by level, until you find an element that matches the selector. If nothing is found, an empty jQuery object is returned.

The syntax is:

Returns the first ancestor element of the selected element:

$(selector).closest(filter)

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

$(selector).closest(filter,context)

Filter is required. Specifies a selector expression, element, or jQuery object that narrows the search for ancestor elements.

Context is optional. DOM elements within which matching elements can be found.

Examples are as follows:

123. ancestors *{ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px;$(document).ready(function(){$("span").closest("ul").css({"color":"red","border":"2px solid red"});});body (great-great ancestor node)div (great-great ancestor node)ul (2nd ancestor-2nd ancestor node) ul (1st ancestor-1st ancestor node)li (direct parent node)span

Output:

"How to use the closest method in jquery" is introduced here. Thank you for reading it. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Tags: Element ancestor method object node expression selection content function more knowledge grammar output utility and so on learning and so on and then dilemma reality situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Microsoft Shulou Information Huawei Linux