Let\'s say I have a collection of \'items\' like so:
You can use a combination of .filter
and .map
to achieve the desired result:
$(".item.group")
.filter(function() {
return !$(this).prev().is(".group");
})
.map(function() {
return $(this).nextUntil(":not(.group)").andSelf();
})
.wrap('');
See it in action.
Example on JS Bin to get around the current JSFiddle problems.
The method .wrap embeds each item inside the current jQuery object inside the markup of your choice. It follows that if you want to wrap multiple elements in the same wrapper you have to match those N elements with a jQuery object and then create another jQuery object that contains one element: the first jQuery object. It is this latter object that you should pass to .wrap
.
So what we need to do here is create one jQuery object for each group and then put all of those into another "master" jQuery object. Begin by selecting all .group
elements that are not themselves preceded by a .group
sibling:
$(".item.group")
.filter(function() {
return !$(this).prev().is(".group");
})
From each such element, create a jQuery object that includes the element and all following siblings with .group
:
.map(function() {
return $(this).nextUntil(":not(.group)").andSelf();
})
The resulting jQuery objects are automatically placed inside the "master" object because they take the place of the bare elements we selected with .filter
inside the jQuery object we created with $(".item.group")
. A final call to .wrap
... wraps things up. :)