jquerywrapallnextuntil

jQuery: Wrap elements with nextUntil()


<h2 id="match" class="contentHeadline">Match only in here</h2>

<p>I don't if or how many dl+table live here.</p>

<dl><dt>Text</dt></dl>
<table class="groupTable"><td>1</td><td>Abc</td></table>

<dl><dt>Text</dt></dl>
<table class="groupTable"><td>2</td><td>Def</td></table>

<dl><dt>Text</dt></dl>
<table class="groupTable"><td>3</td><td>Ghi</td></table>

<p class="foo">Maybe some text lives here. I should not float.</p>

I want to wrap each pair of dl + table in a div.box (floating), but only directly under h2#match until other stuff following (.foo or headlines).

$("dl").each(function(){
    $(this).next('.groupTable').andSelf()
        .wrapAll('<div class="box"></div>');
});

/* Clear */
$('<div class="clear"></div>').after('.box:last');

nextUntil() wraps dl and the table individually.

Atm the test group is wrongly wrapped.

Test: http://jsfiddle.net/GQwB5/

Desired result: http://jsfiddle.net/kppQ9/


Solution

  • $('#match').nextUntil('.contentHeadline') works well.

    Applied:

    $('#match').nextUntil('.contentHeadline').filter('dl').each(function(){
        $(this).next('.groupTable').andSelf().wrapAll('<div class="box" />');
    });
    $('#match').nextUntil('.contentHeadline').filter('.box:last').after('<div class="clear" />');
    

    Fiddle: http://jsfiddle.net/GQwB5/1/

    I suspect that .nextUntil(".foo, .contentHeadline") won't work because it expects a single matching element, and that would return at least two.