Say I have the following markup:
<div class="parent">
<div class="child">
<div class="grand-child">
And I want to get .parent starting from .grand-child. I can do either of the following two:
$('.grand-child').parent().parent();
$('.grand-child').closest('.parent');
Overall, closest() feels like a nicer approach since:
- Only one function
- It is irrelevant to other divs between the
.grand-childand.parent
Specifically, due to advantage of #2 above, if I were to change my markup to
<div class="parent">
<div class="child">
<div class="nanny">
<div class="grand-child">
Then I need to add an extra parent() but closest() still functions fine.
So is there a reason why you would ever choose parent() or closest()?