JQuery Traversing  Descendants

please click here for more wordpress cource

In jQuery, traversing descendants means navigating through the children, grandchildren, great-grandchildren, and so on, of a selected element.

There are several methods available in jQuery for traversing descendants:

  1. children() method: This method selects all the direct children of the selected element.
  2. find() method: This method selects all the descendants of the selected element, not just the direct children.
  3. parent() method: This method selects the immediate parent of the selected element.
  4. parents() method: This method selects all the ancestors of the selected element.
  5. closest() method: This method selects the first ancestor of the selected element that matches a given selector.

Here’s an example that demonstrates the use of these methods:





<div id="parent">
  <div class="child">
    <div class="grandchild"></div>
  </div>
  <div class="child">
    <div class="grandchild"></div>
    <div class="grandchild"></div>
  </div>
</div>
// Select all the direct children of the parent element
$('#parent').children(); // returns a jQuery object containing the two child divs

// Select all the descendants of the parent element
$('#parent').find('*'); // returns a jQuery object containing all the divs inside the parent element

// Select the immediate parent of the grandchild element
$('.grandchild').parent(); // returns a jQuery object containing the two child divs

// Select all the ancestors of the grandchild element
$('.grandchild').parents(); // returns a jQuery object containing the parent and grandparent divs

// Select the closest div with the class "child" that is an ancestor of the grandchild element
$('.grandchild').closest('.child'); // returns a jQuery object containing the parent divs with class "child"

You may also like...

Popular Posts

Leave a Reply

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