Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - parent() vs closest()

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:

  1. Only one function
  2. It is irrelevant to other divs between the .grand-child and .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()?

like image 865
Kousha Avatar asked Jul 27 '14 17:07

Kousha


1 Answers

you should use $('.grand-child').closest('.parent'); because .parent().parent() is strongly based on your html structure if in future you add another div inside one of these then you will get wrong element using parent().parent()

Suppose you have html like:

<div class="parent">
    <div class="child">
        <div class="grand-child-container">
             <div class="grand-child">

now what will happen if you use .parent().parent() it will give you wrong element, so recommended way is to use closest() as it is much better.

According to docs:

parent() gets the parent of each element in the current set of matched elements, optionally filtered by a selector.

closest() For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Differences:

if you scroll little down you can see differences between these two by official jquery site.

There are also some more good answers available on differences between these two:

parent vs closest

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

Performance:

Also performance wise closest() is better than parent(), you can check Benchmark between closest() and parent()

like image 88
Ehsan Sajjad Avatar answered Sep 29 '22 06:09

Ehsan Sajjad