Closest vs Parents

Asked

Viewed 790 times

7

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

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

Reading the differences I noticed this detail in the method closest it looks until it finds the element that matches the sent selector. Already in the method parents, it takes all the elements and adds in a list and then makes the comparison.

Apparently the closest is better, looking performance. Is that true? Is there any case that is better to use the parents?

1 answer

13


Everything will depend on the use.

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

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

Thus, the choice of method is not so much related to the performance itself, but rather to the case you want to use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.