JQuery traversal-about closest () method and Difference Analysis with parents () _ jquery

Source: Internet
Author: User
This article introduces jQuery traversal-methods about closest () and differences between them and parents. If you need a friend, refer to the closest () method to obtain the matching selector. First Ancestor Element, Starting from the current elementAlong the DOM tree.

Syntax:

. Closest (selector)

The selector parameter is a string value that contains the selector expression of the matching element.

Given a jQuery object that represents a DOM element set, the. closest () method allows us to retrieve these elements and their ancestor elements in the DOM tree and construct a new jQuery object with matching elements .. The parents () and. closest () methods are similar. They all traverse up the DOM tree. Although the differences between the two are subtle, they are important:

. Closest () . Parents ()
Starting from the current element Starting with the parent Element
Traverse up the DOM tree until a match of the applied selector is found. Traverse up the DOM tree until the root element of the document adds Each ancestor element to a temporary set. If a selector is applied, the set is filtered Based on the selector.
Returns a jQuery object containing zero or one element. Returns a jQuery object containing zero, one, or more elements.

Let's take a look at the following example: demonstrate how to use closest () to delegate events. When clicked by the closest list element or its child element, the yellow background is switched.

The Code is as follows:





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.