Analysis of the difference between closest and parents in jQuery

  • 2020-06-07 03:59:41
  • OfStack

In jQuery, closest and parents are used to look for elements on the line. But if you don't understand, let's take a look at the differences between closest and parents.

1. The parent

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

Ancestors of 2.

parents(selected) -- All selected ancestors (not containing the root element), which may be 0, 1, or more.
closest(selected) -- only 1 selected ancestor, possibly with 0 or 1 elements.
The main differences between closest and parents are:

The former starts from the current element and the latter from the parent element.

The former looks up until it finds a matching element and stops; the latter 1 looks straight up until the root element, which is then put into a temporary collection and filtered with a given selector expression.

The former returns 0 or 1 elements, while the latter may contain 0, 1, or more elements.

closest is useful for handling event delegates.

conclusion

1. closest lookups start at themselves, and parents starts at the element parent
2. closest looks up and stops searching until it finds a match. parents1 looks up to the root element and adds the matching element to the collection
3. closest returns an jquery object containing zero or one elements, and parents returns an jquery object containing zero or one or more elements

This is the end of this article, I hope you enjoy it.


Related articles: