Pankaj Bhagat Pankaj Bhagat - 18 days ago 7
jQuery Question

using jQuery to select elements until an element has a particular class, apply wrapALL to each set

My html is as below

<input class="beginFlex" name="name1" value="A">
<input name="name2" value="A">
<input class="endFlex" name="name3" value="A">

<input class="beginFlex" name="name1" value="B">
<input name="name4 value="B">
<input name="name5" value="B">
<input name="name6" value="B">
<input class="endFlex" name="name1" value="B">

<input class="beginFlex" name="name1" value="C">
<input name="name7" value="C">
<input name="name8" value="C">
<input class="endFlex" name="name1" value="C">


I want to use jQuery to select groups of elements. The group begins at class beginFlex and ends at endFlex. Then I wan to apply wrapAll() so that I get the code as below:

<div style="display:flex">
<input class="beginFlex" name="name1" value="A">
<input name="name2" value="A">
<input class="endFlex" name="name3" value="A">
</div>

<div style="display:flex">
<input class="beginFlex" name="name1" value="B">
<input name="name4 value="B">
<input name="name5" value="B">
<input name="name6" value="B">
<input class="endFlex" name="name1" value="B">
</div>

<div style="display:flex">
<input class="beginFlex" name="name1" value="C">
<input name="name7" value="C">
<input name="name8" value="C">
<input class="endFlex" name="name1" value="C">
</div>

Answer

Use netUntill to select all elements, use add to select the first and last elements

Try the following

  $('.beginFlex').each(function() {
    $(this).nextUntil('.endFlex').add($(this)).add($(this).nextAll('.endFlex')[0]).wrapAll('<div style="display:flex">');
  });
.flex {
  display: flex;
  border: 1px solid #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="beginFlex" name="name1" value="A">
<input name="name2" value="A">
<input class="endFlex" name="name3" value="A">

<input class="beginFlex" name="name1" value="B">
<input name="name4" value="B">
<input name="name5" value="B">
<input name="name6" value="B">
<input class="endFlex" name="name1" value="B">

<input class="beginFlex" name="name1" value="C">
<input name="name7" value="C">
<input name="name8" value="C">
<input class="endFlex" name="name1" value="C">