Can I $.wrap() around a collection of elements in an array?
Try wrapAll
method instead:
$(".group").wrapAll("<div class='wrap' />");
DEMO: http://jsfiddle.net/LanMt/3/
For wrapping the separate groups of .group
elements you can use the following:
$(".group").map(function() {
if (!$(this).prev().hasClass("group")) {
return $(this).nextUntil(":not(.group)").andSelf();
}
}).wrap("<div class='wrap' />");
DEMO: http://jsfiddle.net/LanMt/5/
The code above was assembled with the help of @Jon's answer.
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('<div class="wrap" />');
See it in action.
Example on JS Bin to get around the current JSFiddle problems.
Rationale
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. :)
Use wrapAll instead of wrap.
$(".group").wrapAll('<div class="wrap" />');
Documentation of wrapAll can be found at - http://api.jquery.com/wrapAll/
Other wrapping methods available can be found at - http://api.jquery.com/category/manipulation/dom-insertion-around/
EDIT:
For the complex case where there can be more than one groups, we can achieve it using wrapAll with a $.each as follows -
var group = [];
$(".item").each(
function(i, item) {
if ($(item).hasClass("group")) {
group.push(item);
}
else {
$(group).wrapAll('<div class="wrap" />');
group = [];
}
}
);