wrapall直接兄弟类到他们自己的div

时间:2014-04-24 11:25:00

标签: javascript jquery traversal siblings

我想将以'ok'开头的直接兄弟组包装到他们自己的组中 http://jsfiddle.net/7hABQ/12/

<div class="foo"></div>
<div class="ok-4"></div>
<div class="ok-87"></div>
<div class="ok-11"></div>
<div class="bar"></div>
<div class="baz"></div>
<div class="ok-5a4"></div>
<div class="ok-12"></div>
<div class="bim">iii</div>

进入这个:

<div class="foo"></div>
<div id="wrapper">
    <div class="ok-4"></div>
    <div class="ok-87"></div>
    <div class="ok-11"></div>
</div>
<div class="bar"></div>
<div class="baz"></div>
<div id="wrapper">
    <div class="ok-5a4"></div>
    <div class="ok-12"></div>
</div>
<div class="bim">iii</div>

1 个答案:

答案 0 :(得分:3)

一种可能的解决方案:

$(':not(div[class^="ok"]) + div[class^="ok"]').each(function() {
    $(this).nextUntil(':not(div[class^="ok"])')
           .addBack()
           .wrapAll('<div class="wrapper"></div>');
});

DEMO: http://jsfiddle.net/7hABQ/18/