Closest vs Parents

7

I was reading the jQuery documentation and I finally noticed the similarity between the closest and parents methods.

He cites the differences between the methods, stating that "they are subtle but significant."

Reading the differences I noticed this detail in the closest method it will search until it finds the element that corresponds to the selector sent. In the parents method, it takes all the elements and adds them to a list and then compares them.

Apparently closest is better looking at performance. That's true? Is there any case that it is better to use parents ?

    
asked by anonymous 09.05.2014 / 21:45

1 answer

11

Everything will depend on usage.

The JQuery documentation itself explains the differences through a comparative table .

  • The closest method starts the search in the element itself, while the parents method starts in the parent element
  • The closest method searches until it finds an element that satisfies the selector (and can be itself), while the parents method will add all the element's parents to a list and then filter the list to return the elements that satisfy the
  • The closest method will return one or no element, while the parents method will return any or a list of elements, in the reverse order as explained in the document

In this way, the choice of method is not so much related to the performance itself, but rather to the case one wishes to use.

    
09.05.2014 / 22:02