Http://www.poluoluo.com/jzxy/201312/253059.html
In this sprint, jquery is used for writing the front-end UI, but jquery has parents (), parent (), and closest () in the API to walk up the DOM tree, and it's not clear what the difference is, So hard to read a bit of jquery's API document, and the difference is recorded here for reference.
1.parents ([selector])
This method is used to select the ancestor nodes of the DOM element or set of DOM elements that are contained in a given jquery object, and wrap the nodes as a jquery object, returning the set of nodes that are sorted in the order from the inside out.
Also, this method accepts a string selector that filters the set of child elements that conform to the selector from the returned set of nodes.
2.parent ([selector])
This method is used to select the parent node of the DOM element or set of DOM elements that are contained in a given jquery object. It differs from parents () in that it searches only one layer upwards, while parents () searches the entire DOM tree.
This method can also accept a string selector, which is used to filter the returned elements.
One might ask: Is there not only one DOM element's parent element, why do you want a selector selector to filter it? In fact, a jquery object may contain a number of DOM elements, such as $ (' a '). The parent () selects all of the <a> tag's parents so that it returns an element set so that it can be filtered.
3.closest (selector)
This method is used to iterate up the DOM elements contained in the JQuery object or the ancestor nodes of the set of DOM elements 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 returned jquery object contains 0 or 1 objects;
Parents () walks up from its parent node, returns all ancestor nodes, and filters the nodes based on the selector, and eventually the jquery object returned may contain 0, 1, or more objects.
An example to illustrate the difference:
.The code is 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 with elements such as span, p, Div, body, and HTML;
$ (' B '). The parent () will return: The jquery object constructed by span;
$ (' B '). Closest (' div ') will return: The jquery object constructed by the Div.
jquery traverses the DOM tree parents (), the difference between the parent (), closest ()