Saturday, October 12, 2013

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'

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Receive all updates via Facebook. Just Click the Like Button Below

You can also receive Free Email Updates: