Reputation: 1511
I have multiple rows for which I can't change the structure or attributes. But I can add child elements (.start
& .end
) in these rows.
So I want to wrap all elements after a row with a .start
child element until the next row has an .end
child element. I created an each
loop to achieve this. But the problem is that the closing div of my wrap is one level too deep.
As you can see in the following snippet, the border goes around all elements after the .start
element, but it should only be around 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>
Upvotes: 0
Views: 208
Reputation: 207491
You want to use :has()
selector
$(this).nextUntil(".row:has('.end')")
Upvotes: 6