I have some HTML that looks like this:
<p>Some Text</p>
<div class="listBullet">Item 1</div>
<div class="listBullet">Item 2</div>
<div class="listBullet">Item 3</div>
<p>Some More Text</p>
<div class="listBullet">Item 1</div>
<div class="listBullet">Item 2</div>
<div class="listBullet">Item 3</div>
<p>Some Other Text</p>
I want to end up with the following output:
<p>Some Text</p>
<div class="wrapperDiv">
<div class="listBullet">Item 1</div>
<div class="listBullet">Item 2</div>
<div class="listBullet">Item 3</div>
</div>
<p>Some More Text</p>
<div class="wrapperDiv">
<div class="listBullet">Item 1</div>
<div class="listBullet">Item 2</div>
<div class="listBullet">Item 3</div>
</div>
<p>Some Other Text</p>
I tried $(".listBullet").wrapAll("<div class='wrapperDiv' />")
, but that ended up moving the two blocks to be contiguous with each other. It seems like what I need is a selector that separates the contiguous blocks into separate elements, which I would then call wrapAll on separately.
This does the job:
$('p + .listBullet').each(function() {
$(this).nextUntil('p')
.addBack()
.wrapAll("<div class='wrapperDiv' />");
});
Fiddle 1
container
is the class of the parent div
):
$('.container > :not(.listBullet) + .listBullet').each(function() {
$(this).nextUntil('.container > :not(.listBullet)')
.addBack()
.wrapAll("<div class='wrapperDiv' />");
});
Fiddle 2
var lb= [];
$('.container > *').each(function() {
if($(this).hasClass('listBullet')) {
lb.push(this);
}
else {
$(lb).wrapAll("<div class='wrapperDiv'/>");
lb= [];
}
});
$(lb).wrapAll("<div class='wrapperDiv'/>");
Fiddle 3
As a general approach you could:
Loop through all the elements on the page using .next()
, while the next element you find is has the correct class, (use .attr("class")
) add an extra class of currentList
(or simular) class wrapAll on currentList
then select all the items with the currentList
class and remove that class and then keep looping!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With