Home >Web Front-end >JS Tutorial >Analysis of the difference between closest and parents in jQuery_jquery

Analysis of the difference between closest and parents in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:00:311133browse

In terms of performance, closest and parents in jQuery both mean to find some content of the online element, but if you look carefully, you may not understand. Let’s take a look at the difference between closest and parents.

1. Parent

parent() - the only parent element, which may be 0 or 1 elements.

2. Ancestors

parents(selected) - all selected ancestors (excluding root elements), which may be 0, 1 or more elements.
closest(selected) - the only selected ancestor, which may be 0 or 1 elements.
The main difference between closest and parents is:

The former starts matching and searching from the current element, and the latter starts matching and searching from the parent element;

The former searches upwards step by step until it finds a matching element and stops. The latter searches upwards until the root element, then puts these elements into a temporary collection, and then uses the given selector expression to filter ;

The former returns 0 or 1 elements, and the latter may contain 0, 1, or multiple elements.

closest is useful for handling event delegation.

Summary

1. The closest search starts with itself, and parents starts with the parent of the element
2. Closest searches upwards and stops searching when it finds a match. Parents searches all the way to the root element and adds the matching elements to the collection
3. closest returns a jquery object containing zero or one element, and parents returns a jquery object containing zero or one or more elements

The above is the entire content of this article, I hope you all like it.

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