Issue
I have a container that contain multiple repeating with same two class: First, second
like below.
<div id="wrapper">
<span class="first"></span>
<span class="second"></span>
<span class="first"></span>
<span class="second"></span>
<span class="first"></span>
<span class="second"></span>
<span class="first"></span>
<span class="second"></span>
</div>
I want to group this two span two by two in a new div with specific id: new (for example)
<div id="wrapper">
<div id="new">
<span class="first"></span>
<span class="second"></span>
</div>
<div id="new">
<span class="first"></span>
<span class="second"></span>
</div>
<div id="new">
<span class="first"></span>
<span class="second"></span>
</div>
<div id="new">
<span class="first"></span>
<span class="second"></span>
</div>
</div>
This is what I do
var evens = $("#wrapper > span:even");
var odds = $("#wrapper > span:odd");
var i = 0;
odds.each(function () {
$(this).add(evens[i]).wrapAll('<span clas="good" style="background-color: red; margin-bottom:40px;"></span>');
i++;
});
What is the best way to do this purpose in jQuery, using name of the class (first, second) and not even and odd ?
Solution
$("#wrapper .first").each((i, el) => {
$(el).nextUntil(".first").addBack().wrapAll(`<div class="wrap" />`)
});
#wrapper .wrap {
outline: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<span class="first">1</span>
<span class="second">2</span>
<span class="first">1</span>
<span class="second">2</span>
<span class="first">1</span>
<span class="second">2</span>
<span class="third">3</span>
<span class="first">1</span>
<span class="second">2</span>
</div>
Answered By – Roko C. Buljan
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0