Differences between closest and parents in jQuery
This article introduces the usage and differences between parents () and closest () in jquery. When you find that parents () in jquery deletes a parent element, it finds that it does not contain the root element, so closest () is used, and the effect is good. Let me introduce it to you in detail.
In jQuery, closest and parents refer to searching for some content of online elements in terms of performance, but if you may not understand it carefully, let's take a look at the differences between closest and parents.
1. Parent level
Parent () -- Unique parent element, which may be 0 or 1 element.
2. Ancestor
Parents (selected) -- all selected ancestors (excluding root elements), which may be 0, 1, or multiple elements.
Closest (selected) -- Unique selected ancestor, which may be 0 or 1 element.
The main differences between closest and parents are:
The former matches the current element and the latter matches the parent element;
The former searches up one by one until the matching elements are found and then stops. The latter searches up until the root elements are put into a temporary collection, filter with the given selector expression;
The former returns 0 or 1 element, and the latter may contain 0, 1, or multiple elements.
Closest is very useful for handling event delegation.
Summary
1. closest lookup begins with itself, and parents begins with the element parent level.
2. closest searches up. If you find a match, stop searching. parents searches for the root element and adds the matched element to the set.
3. closest returns a jquery object containing zero or one element. parents returns a jquery object containing zero or one or more elements.
The above is all the content of this article. I hope you will like it.
Note <>: For more exciting tutorials, please pay attention to the help house programming