我有一大堆DOM,其中包含div,其中“foo”类跟在“bar”之后的某个位置,就像这样......
<div class="kev">...</div>
<div class="foo">...</div>
<div class="bob">...</div>
<div class="tom">...</div>
<div class="bar">...</div>
<div class="pat">...</div>
<div class="foo">
<div class="tim">...</div>
<div class="foo">...</div>
<div class="jim">...</div>
<div class="bar">...</div>
<div class="rob">...</div>
</div>
<div class="meg">...</div>
<div class="bar">...</div>
我希望它包装所有以“foo”开头并以“bar”结尾的类,就像这样......
<div class="kev">...</div>
<div class="wrapper">
<div class="foo">...</div>
<div class="bob">...</div>
<div class="tom">...</div>
<div class="bar">...</div>
</div><!--end of wrapper-->
<div class="pat">...</div>
<div class="wrapper">
<div class="foo">
<div class="tim">...</div>
<div class="wrapper">
<div class="foo">...</div>
<div class="jim">...</div>
<div class="bar">...</div>
</div><!--end of wrapper-->
<div class="rob">...</div>
</div>
<div class="meg">...</div>
<div class="bar">...</div>
</div><!--end of wrapper-->
注意:它们可以嵌套,如上所述。
任何帮助非常感谢
答案 0 :(得分:3)
尝试以下方法:
$(".foo").each(function () {
$(this).nextUntil(".bar + *").addBack().wrapAll("<div class='wrapper'/>");
});
答案 1 :(得分:1)
$.each($(".foo"), function() {
var untilBar = $(this).nextUntil(".bar").addBack(); //Select .foo div and it's siblings until .bar
untilBar.add(untilBar.next()).wrapAll('<div class="wrapper"></div>'); //Add .bar to the set and wrap
});
请看这个小提琴:http://jsfiddle.net/BYxHL/