jquerynextuntil

How to target nearest class within a container using jquery?


I want to target the nearest class and stop on targeting other class elements if it's the last item to be read on that part. Here is what I am trying to achieve.

enter image description here

The .is-child class will show if the .parent class is clicked and only the nearest class will be shown. I already tried using .next() method but it will only show 1 .is-child element per click

Here is my code:

    jQuery('li.current.parent').click(function(){
         jQuery(this).next('.is-child').css('display', 'block');
    });

I also tried using .nextAll but it will show all of the .is-child element.

    jQuery('li.current.parent').click(function(){
         jQuery('.is-child').nextAll('.is-child').css('display', 'block');
    });

Solution

  • You need to select the elements using .nextUntil - This will select all the element from $(this) until the specified selector (Not including $(this) AND that element that match to the selector):

    $(function() {
      jQuery('li.current.parent').click(function(){
        jQuery(this).nextUntil('.parent').css('background-color', 'red');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
      <li class="current parent">click here</li>
      <li class="is-child">hi</li>
      <li class="is-child">hi</li>
      <li class="is-child">hi</li>
      <li class="parent">bye</li>
    </ul>