Parents of jQuery traverse up the DOM tree the parent of the closest of the difference between

  • 2020-03-30 00:38:33
  • OfStack

In this sprint, because want to write the front-end UI, so with the help of jQuery, but jQuery in API, traverse the DOM tree up with parents (), the parent (s), the closest () these a few, has not been very clear on the difference between the their concrete, so be a good read on the jQuery API documentation, and write difference here, for your reference.

  1. Parents ([selector])

This method is used to select the ancestor nodes of DOM elements or sets of DOM elements contained in a given jQuery object and wrap these nodes back as jQuery objects, with the returned set of nodes sorted from the inside out.

This method also accepts a string selector to filter the set of child elements that match the selector from the returned set of nodes.

  2. The parent ([selector])

This method is used to select the parent node of a DOM element or set of DOM elements contained in a given jQuery object. Unlike parents(), which searches only one layer up, parents() searches the entire DOM tree.

This method can also accept a string selector to filter the returned elements.

One might ask: why would you want a selector selector to filter a DOM element if it has only one parent? In fact, a jQuery object may contain many DOM elements, such as $('a').parent() selects all < A> The parent element of the tag, which returns a set of elements, so you can filter.

  3. The closest (the selector)

This method is used to iterate up through the ancestor node of a DOM element or set of DOM elements contained in a jQuery object until a node that matches the selector selector is found.

The difference between it and parents:

Closest () from their own start up traversal, until you find a suitable node, return the jQuery object contains zero or one object;

Parents () iterate up from their parent nodes, return all the ancestor nodes, filter them according to the selector, and eventually return jQuery objects that may contain 0, 1, or more objects.

  An example of the difference:

<!DOCTYPE html>
    <title>a test document</title>
                <b>My parents</b>

In the above document:

$('b').parents() will return: jQuery object constructed by elements such as span, p, div, body, HTML, etc.

$('b').parent() returns: jQuery object constructed by span;

$(" b "). The closest (' div ') returns: by div structure of the jQuery object.

Related articles: