jQuery/js wrap near div with same classes into single div
Loop through .heading
elements using .each()
and in loop select .item
that is next to each other using .nextUntil()
and then wrap them using .wrapAll()
$(".heading").each(function(){
$(this).nextUntil(".heading").wrapAll("<div></div>");
});
.heading + div {background: #ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section">
<div class="heading">heading</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="heading">heading</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="heading">heading</div>
<div class="item">item</div>
<div class="heading">heading</div>
<div class="item">item</div>
<div class="item">item</div>
</div>
try
let h,s= document.querySelector('.section');
[...s.children].forEach(e=> {
if(e.className=='heading') {
h=document.createElement("div")
e.insertAdjacentElement('afterend',h)
} else {
h.appendChild(e)
}
})
function change() {
let h,s= document.querySelector('.section');
[...s.children].forEach(e=> {
if(e.className=='heading') {
h=document.createElement("div")
e.insertAdjacentElement('afterend',h)
} else {
h.appendChild(e)
}
})
}
div { margin-left: 30px;}
<button onclick="change()">Click here to change</button>
<div class="section">
<div class="heading">head 1</div>
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="heading">head 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="heading">head 3</div>
<div class="item">item 5</div>
<div class="heading">head 4</div>
<div class="item">item 6</div>
<div class="item">item 7</div>
</div>