parent, parents, closest. What is the difference ?

All these 3 jQuery methods are used for navigating upwards through the DOM. But they all are different from each other in ways that make them each uniquely useful, Here’s a tiny bit of explanation.

.parent()
– Matches the one immediate parent of the element(s)
– Optionally filtered by a selector.
eg:
<div class=”first”>
  <div class=”second”>
    <div class=”third”>
      <div class=”fourth”></div>
    </div>
  </div>
</div>
$(‘.fourth’).parent(); // this will select div with the class ‘third’ which is parent of the div with class ‘fourth’

.parents()
– It is not restricted to just one level above the matched element(s).
– It can return multiple ancestors.
– Optionally filtered by a selector.
eg.
<div class=”first”>
  <div class=”second”>
    <div class=”third”>
      <div class=”fourth”></div>
    </div>
  </div>
</div>
$(‘.fourth’).parents(); // this will return all the div elements which are parent of the div with class ‘fourth’

.closest()
– It works like parents(), except that it returns only one parent/ancestor.
– Get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
eg.
<div class=”first”>
  <div class=”second”>
    <div class=”third”>
      <div class=”fourth”></div>
    </div>
  </div>
</div>
$(‘.fourth’).closest(‘.second’); // this will return the div element with class ‘second’ which is one of the parent of div with class ‘fourth’

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.