Currently, I am dealing with multiple rows that have a fixed structure and attributes. However, I have the flexibility to insert child elements (.start
& .end
) within these rows.
My goal is to enclose all elements following a row with a .start
child element until the subsequent row contains an .end
child element. To achieve this, I designed an iteration using the each
method. Unfortunately, I encountered an issue where the closing div of my wrapping is nested too deeply.
In the code snippet below, you can observe that the border encompasses all elements after the .start
element, when it should only surround rows 3, 4, and 9.
$('.row .start').closest('.row').each(function (index) {
$(this).nextUntil(".row .end").wrapAll("<div class='box'/>");
});
.box{
border: 1px solid red;
background-color:pink;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="element">1</div>
</div>
<div class="row">
<div class="element">
<div class="start">start</div>
</div>
</div>
<div class="row">
<div class="element">3</div>
</div>
<div class="row">
<div class="element">4</div>
</div>
<div class="row">
<div class="element">
<div class="end">end</div>
</div>
</div>
<div class="row">
<div class="element">6</div>
</div>
<div class="row">
<div class="element">7</div>
</div>
<div class="row">
<div class="element">
<div class="start">start</div>
</div>
</div>
<div class="row">
<div class="element">9</div>
</div>
<div class="row">
<div class="element">
<div class="end">end</div>
</div>
</div>