I have a somewhat grouping system which all the elements between two divs are grouped together. See the code below to see what I'm trying to say:
$(document).ready(function(){
var groupo = $('div').filter(function(){return $(this).text().match(/\[group\]/)}); //finds "[group]"
var groupc = $('div').filter(function(){return $(this).text().match(/\[\/group\]/)}); //finds "[/group]"
groupc.addClass("groupclose"); //adds the class groupclose so that it can be used by nextUntil
groupo.nextUntil(".groupclose").wrapAll('<div class="group"></div>');
groupo.remove();
g开发者_Go百科roupc.remove();
});
When the HTML is:
<div>[group]</div>
<div>first</div>
<div>second</div>
<div>[/group]</div>
it works just fine, but when there are two or more 'groups' the wrapAll wraps them together, for example:
<div>[group]</div>
<div>first</div>
<div>second</div>
<div>[/group]</div>
<div>[group]</div>
<div>this is in</div>
<div>another group</div>
<div>which get wrapped together with the one above</div>
<div>[/group]</div>
The problem is similar to this wrapAll jQuery problem but in that case we know the number of divs in a set, while in this case we don't.
Any ideas?
Edit: added the link to jsbin http://jsbin.com/ejepu3
I think you just needed to loop through the contents of groupo
. Also, no need to use filter()
. You can use the :contains('')
selector
var groupo = $("div:contains('[group]')");
var groupc = $("div:contains('[/group]')").addClass("groupclose");
$(groupo).each(function(){
$(this).nextUntil(".groupclose").wrapAll('<div class="group"></div>');
});
groupo.remove();
groupc.remove();
working version: http://jsfiddle.net/48Pfp/2/
精彩评论