Reputation: 80
I'm working with .wrap()
and .wrapAll()
jQuery, but I can't seem to figure out a solution to the manipulating the code below.
I am working with so not-so-great markup and I'm trying to figure out how I can turn the following HTML:
<p class="category">Category 1</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="category">Category 2</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="category">Category 3</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
Into this:
<div class="category-1">
<p class="category">Category 1</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
</div>
<div class="category-2">
<p class="category">Category 2</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
</div>
<div class="category-3">
<p class="category">Category 3</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
</div>
I need to wrap from one .category
to the next. I don't need the div that wraps each section to necessarily be the category name, I just named it that way for this question.
Upvotes: 0
Views: 79
Reputation: 115212
Iterate over the .category
and then wrap elements by getting up to the next .category
element.
$('.category').each(function(i) {
$(this)
// get element up to the next `.category`
.nextUntil('.category')
// in case there is any other element as the sibling
// then only get the paragraph element using
// .filter('p.item')
// add the current element to the object
.add(this)
// wrap it using the div
.wrapAll($('<div/>', {
class: 'category' + (i + 1)
}))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="category">Category 1</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="category">Category 2</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="category">Category 3</p>
<p class="item">Item</p>
<p class="item">Item</p>
<p class="item">Item</p>
</div>
Upvotes: 5