Is there a way to reach parent's sibling in jquery?

Issue

I have a button inside a div. When clicked, i will need to grab the length of a list that is a sibling to the parent container. maybe so even a grandparent container.

The gist of the code looks something like this below. (My actual code is actually nested deeper than this example. I would like to know how to target part a sibling of a parent or grandparents or even great great grandparent…)

HTML

<div>
  <div class="button-parent">
    <div class="button-containers">
      <button>Click Here!</button>
    </div>
  </div>
  <div class="list-container">
    <ul class="lists">
      <li>bar</li>
      <li>bar</li>
      <li>bar</li>
      <li>bar</li>
      <li>bar</li>
    </ul>
  </div>
</div>

jquery

$('button').parent('button-parent')
           .closest('list-containers').length

Solution

.closest() finds the closest ancestor (parent), so it won’t find your .list-container.

You can do this a few ways though…

  1. Give your surrounding div a class and use .find() to locate your list if it is the only list in your parent div:

     $('button').closest('.parent-div').find('.list-container');
    
  2. Use next() if .list-container will always be the next item after .button-parent:

     $('button').closest('.button-parent').next('.list-container');
    
  3. You can use .siblings() if .list-container will always be on the same DOM level as .button-parent:

     $('button').closest('.button-parent').siblings('.list-container');
    

From there you can fulfil the rest of your requirement to capture the length of the list by selecting all the li elements and counting them. If we use number 1 above as an example, it might look something like this:

const list = $('button').closest('.parent-div').find('.lists');
const items = list.children();
const count = items.length;

NOTE: The selection for list in this example targets ul.lists rather than .list-container, as this allows us to count using children(), which is much less intensive than find().

Answered By – DoubleA

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.