How can I wrap inner divs that are dynamic?

I have been trying badly to wrap some divs with an outer div so that I can style them. But I’m unable to do so thus far.

I have this list div which contains some inner divs that I need to wrap. That is the inner divs which have same letters need to be bundled together. Although targeting the divs with the letters is not a good idea as they are gonna be dynamic.

This is an example of what I have been trying to achieve:

<div class="list-wrapper">
    <div class="el">A</div>
    <div> 
       <a>A</a>
    </div>
</div>

<div class="list-wrapper">
    <div class="el">C</div>
    <div> 
       <a>C</a>
    </div>
    <div> 
       <a>C</a>
    </div>
</div>

Another example:

enter image description here

This is what I have tried so far:

$(list).find('div.el').each(function(idx, item) {
  $(item).nextAll('div').wrapAll('<div class="list-wrapper"></div>')
});
.wrapper {
  background-color: red;
  padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">

  <div class="el">A</div>
  <div>
    <a>A</a>
  </div>

  <div class="el">B</div>
  <div>
    <a>B</a>
  </div>

  <div class="el">C</div>
  <div>
    <a>C</a>
  </div>
  <div>
    <a>C</a>
  </div>

  <div class="el">D</div>
  <div>
    <a>D</a>
  </div>
  <div>
    <a>D</a>
  </div>
  <div>
    <a>D</a>
  </div>

  <div class="el">E</div>
  <div>
    <a>E</a>
  </div>

</div>

Answer

To achieve your goal you can use a combination of nextUntil() within the loop, to get the div elements between each .el, and wrapAll(). You can include addBack() in there to add the current .el in the loop in to the collection to be wrapped. Try this:

$('#list').find('.el').each((i, el) => {
  $(el).nextUntil('.el').addBack().wrapAll('<div class="list-wrapper"></div>')
});
.wrapper {
  background-color: red;
  padding: 20px;
}

.list-wrapper { border: 1px solid #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
  <div class="el">A</div>
  <div><a>A</a></div>

  <div class="el">B</div>
  <div><a>B</a></div>

  <div class="el">C</div>
  <div><a>C</a></div>
  <div><a>C</a></div>

  <div class="el">D</div>
  <div><a>D</a></div>
  <div><a>D</a></div>
  <div><a>D</a></div>

  <div class="el">E</div>
  <div><a>E</a></div>
</div>

Note that $(list) was only working by proxy, as elements with an id attribute are available as properties on the document. It’s much better practice to use a valid string selector.

Leave a Reply

Your email address will not be published. Required fields are marked *