WrapAll jQuery problem
I need to wrap three divs in one, but this group of three divs is repeated multiple times in the code. Maybe my HTML will explain:
<div class="one" />
<div class="two" />
<div class="three" />
<div class="one" />
<div class="two" />
<div class="three" />
I am trying to achieve this:
<div class="wrap">
<div class="one" />
<div class="two" />
<div class="three" />
</div>
<div class="wrap">
<div class="one" />
<div class="two" />
<div class="three" />
</div>
This wraps everything in one div:
$('.one, .two, .three').wrapAll('<div class="wrap" />')
How can I gather groups separately?
+2
source to share
5 answers
$(function(){
var all = $('.one, .two, .three');
for(i=0; i<all.length; i+=3){
all.slice(i,i+3).wrapAll('<div class="wrap" />');
}
});
See it in action: http://jsbin.com/uqosa/
By the way, <div class="one" />
didn't work for me in Firefox, I had to close them with </div>
.
+5
source to share
$.fn.matchUntil = function(expr) {
var match = [];
this.each(function(){
match = [this];
for ( var i = this.nextSibling; i; i = i.nextSibling ) {
if ( i.nodeType != 1 ) { continue; }
if ( $(i).filter(expr).length > 0 ) { break; }
match.push( i );
}
});
return this.pushStack( match );
};
using:
$(".one").each( function() {
$(this).matchUntil(".one").wrapAll("<div class='wr'></div>");
})
this is just a modified version of http://docs.jquery.com/JQuery_1.2_Roadmap#.nextUntil.28.29_.2F_.prevUntil.28.29 which doesn't seem to work with the new jQuery.
0
source to share