13

I have a DOM in the form of

<input class="parent"></div>
<input class="child"></div>
<input class="child"></div>
<input class="parent"></div>
<input class="child"></div>
...

which I know is not Right and the right way to do this would be to reform the HTML, but lets say that is not possible.

How can I get jquery to select all children of one parent (that is select all .children until .parent)

jon skulski
  • 2,305
  • 3
  • 18
  • 27

4 Answers4

25

jQuery 1.4 now has the .nextUntil(selector) function:

    $('div.parent').toggle(
        function() {
            $(this).nextUntil('div.parent').hide();
         },
        function() {
            $(this).nextUntil('div.parent').show();
        }
    );
foson
  • 10,037
  • 2
  • 35
  • 53
8

You can iterate through the nextAll div siblings elements until you find the following .parent, check this example:

$('.parent').click(function() {
  $(this).nextAll('div').each(function() {
    if ($(this).is('.parent')) {
      return false; // next parent reached, stop
    }
    $(this).toggleClass('highlight');
  });
});

Markup used:

<div class="parent">parent 1</div>
<div class="child">child</div>
<div class="child">child</div>
<div class="parent">parent 2</div>
<div class="child">child</div>
<div class="parent">parent 3</div>
<div class="child">child</div>
<div class="child">child</div>
<div class="child">child</div>

...

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • I will give this another shot. I had done it this way but it caused much slowness, due to some extra DOM element I didn't include (wrappers). I didn't think to just return false (I did checks all the way around). I will optimize and try it again. Thanks! – jon skulski Dec 02 '09 at 00:34
  • This was a huge help. Thank you! – BradTheBluefish Nov 15 '21 at 00:31
6

* See @foson answer for jquery 1.4+ *

Check out Ben Almans until utils.

It gives you 3 usefull methods: nextUntil, prevUntil, parentsUntil.

redsquare
  • 78,161
  • 20
  • 151
  • 159
0

I think no need for the above custom functions, JQuery supports this functionality by nextUntil(selector, filter) function, but you should add filter to only apply your script to the filtered elements not to all next elements:

//hide all .child elements
$('div.child').hide();
$('div.parent').click(function() {
  //Toggle (show or hide) only .child elements until finding .parent element.
  $(this).nextUntil('div.parent', 'div.child').slideToggle('slow');
});
Omar Alahmed
  • 1,082
  • 12
  • 13