Home >Web Front-end >JS Tutorial >The difference between parents(), parent(), closest() in jQuery traversing the DOM tree upward_jquery
In this sprint, because we need to write the front-end UI, jQuery is used. However, jQuery’s API for traversing the DOM tree upwards includes parents(), parent(), and closest(). It has never been clear. There are specific differences between them, so I took the trouble to read the jQuery API documentation carefully and recorded the differences here for reference.
1.parents([selector])
This method is used to select the ancestor nodes of the DOM element or DOM element set contained in the given jQuery object, and package these nodes into jQuery objects and return them. The returned node set is sorted from the inside to the outside.
At the same time, this method also accepts a string selector, which is used to filter the set of child elements that match the selector from the returned node set.
2.parent([selector])
This method is used to select the parent node of the DOM element or DOM element set contained in the given jQuery object. The difference between it and parents() is that it only searches one level upward, while parents() searches the entire DOM tree.
This method can also accept a string selector to filter the returned elements.
Someone may ask: Isn’t there only one parent element of a DOM element? Why do we need a selector for filtering? In fact, a jQuery object may contain many DOM elements. For example, $('a').parent() selects the parent elements of all tags. This returns an element set, so it can be filtered.
3.closest(selector)
This method is used to traverse upward the DOM elements contained in the jQuery object or the ancestor nodes of the DOM element set until a node that matches the selector is found.
The difference between it and parents():
closest() starts from itself and traverses upward until it finds a suitable node. The returned jQuery object contains 0 or 1 objects;
parents() starts from its own parent node and traverses upwards, returns all ancestor nodes, and filters these nodes according to the selector. The final returned jQuery object may contain 0, 1 or more objects.
An example to illustrate the difference:
$('b').parent() will return: jQuery object constructed by span;
$('b').closest('div') will return: jQuery object constructed from div.