Difference between jQuery parent(), parents() and closest() functions

closest() selects the first element that matches the selector, up from the DOM tree. Begins from the current element and travels up.

parent() selects one element up (single level up) the DOM tree.

parents() method is similar to parent() but selects all the matching elements up the DOM tree. Begins from the parent element and travels up.


from http://api.jquery.com/closest/

The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements

.parent()

  • Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.

Here are related threads:

  • What's the difference between .closest() and .parents('selector')?

  • https://stackoverflow.com/a/2200805/149206

Tags:

Jquery