In this sprint, jquery is used to write the front-end UI, but jquery has parents (), parent (), closest () in the API to traverse the DOM tree up, and has been unclear about their specific differences. So take a hard look at the jquery API document, and write down the difference here for reference.
1.parents ([selector])
This method is used to select the ancestor nodes of a DOM element or DOM element set that is contained in a given jquery object, and to wrap those nodes back into a jquery object, and the returned node sets are sorted in order from inside to outside.
Also, this method accepts a string selector that filters the set of child elements that match the selector from the returned set of nodes.
2.parent ([selector])
This method is used to select a DOM element or a parent node of a DOM element set that is contained in a given jquery object. Unlike parents (), it searches only one layer up, while parents () searches the entire DOM tree.
This method can also accept a string selector to filter the returned elements.
One might ask: isn't there only one parent element of a DOM element, and why should a selector selector filter it? In fact, a jquery object might contain a number of DOM elements, such as $ (' a '). Parent () is to select all the <a> tags of the parents, so return is a set of elements, so you can filter.
3.closest (selector)
This method is used to iterate up the DOM elements contained in the JQuery object or the ancestor nodes of the DOM element set until a node that conforms to the selector selector is found.
The difference between it and parents ():
Closest () iterates up from itself until a suitable node is found, and the jquery object returned contains 0 or 1 objects;
Parents () starts up through its own parent node, returns all ancestor nodes, and filters the nodes according to the selector, and the final jquery object returned may contain 0, 1, or more objects.
An example that can illustrate the difference:
Copy Code code as follows:
<! DOCTYPE html>
<title>a Test document</title>
<body>
<div>
<p>
<span>
<b>my parents</b>
</span>
</p>
</div>
</body>
In the above document:
$ (' B '). Parents () will return: A jquery object constructed from spans, p, Div, body, HTML, and so on;
$ (' B '). Parent () will return: A jquery object constructed from span;
$ (' B '). Closest (' div ') returns: A jquery object constructed by a Div.