Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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; }
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid="list"><divclass="el">A</div><div><a>A</a></div><divclass="el">B</div><div><a>B</a></div><divclass="el">C</div><div><a>C</a></div><div><a>C</a></div><divclass="el">D</div><div><a>D</a></div><div><a>D</a></div><div><a>D</a></div><divclass="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.

Post a Comment for "How Can I Wrap Inner Divs That Are Dynamic?"