Home > OS >  Wrap multiple repeating elements into same container
Wrap multiple repeating elements into same container

Time:10-11

I have a container that contain multiple repeating with same two class: First, second like below.

<div id="wrapper">
    <span ></span>
    <span ></span>
    <span ></span>
    <span ></span>
    <span ></span>
    <span ></span>
    <span ></span>
    <span ></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 ></span>
        <span ></span>
    </div>
    <div id="new">
        <span ></span>
        <span ></span>
    </div>
    <div id="new">
        <span ></span>
        <span ></span>
    </div>
    <div id="new">
        <span ></span>
        <span ></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 ?

CodePudding user response:

$("#wrapper .first").each((i, el) => {
  $(el).nextUntil(".first").addBack().wrapAll(`<div  />`)
});
#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 >1</span>
    <span >2</span>
    <span >1</span>
    <span >2</span>
    <span >1</span>
    <span >2</span>
    <span >3</span>
    <span >1</span>
    <span >2</span>
</div>

  • Related