In this sprint, jQuery is used because the front-end UI is to be written, but in the APIs that traverse the DOM tree up, there are parents (), parent (), closest () these differences have never been quite clear, so I carefully read the jQuery API documentation and keep the differences here for reference.
1. parents ([selector])
This method is used to select the DOM elements contained in a given jQuery object or the ancestor nodes of the DOM Element Set, and encapsulate these nodes into jQuery objects for return, the returned node set is sorted from the inside out.
At the same time, this method also accepts a string selector to filter child element sets 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 a given jQuery object. Unlike parents (), parents () searches for only one level above and parents () searches for the entire DOM tree.
This method can also accept a string selector to filter the returned elements.
Some may ask: isn't the parent element of a DOM element only one? Why does it need a selector for filtering? In fact, a jQuery object may contain many DOM elements, such as $ ('A '). parent () is to select the parent element of all <a> tags. In this way, a metadata set is returned, so you can filter the elements.
3. closest (selector)
This method is used to traverse up the DOM element contained in the jQuery object or the ancestor node of the DOM element set until the node that matches the selector is found.
It differs from parents:
Closest () traverses from the beginning until a suitable node is found. The returned jQuery object contains 0 or 1 objects;
Parents () traverses up from its parent node, returns all ancestor nodes, and filters these nodes based on the selector. The final returned jQuery object may contain 0, 1, or multiple objects.
An example to illustrate the difference:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> a test document </title>
</Head>
<Body>
<Div>
<P>
<Span>
<B> My parents </B>
</Span>
</P>
</Div>
</Body>
</Html>
In the above documents:
$ ('B'). parents () returns a jQuery object constructed by elements such as span, p, div, body, and html;
$ ('B'). parent () returns the jQuery object constructed by span;
$ ('B'). closest ('div ') returns the jQuery object constructed by div.