I have been using jQuery for a while. I wanted to use the parent()
selector. I also came up with the closest()
selector. Could not find any difference between them. Is there any? If yes, what?
What is the difference between parent()
, parents()
and closest()
?
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
parentNode is native JS, where parent() is not. What you are doing in your code is wrapping the DOM elements in the jQuery object so you can call jQuery specific methods on it. So, you cannot call index() on just this. parentNode, but you can call it on $(this. parentNode).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With