floor
floor

Reputation: 1572

In jQuery how can I wrap multiple elements with a div given that I have a start and end class

Okay so here is some html. I have a few start and end classes but for the sake of this I have only added 1 of each.

<div id="DaySchedule_5amDetail">
    <span>&nbsp;</span>
</div>
<div id="DaySchedule_6amDetail">
    <span>&nbsp;</span>
</div>
<div id="DaySchedule_7amDetail" class="start"> <-- start
    <span>&nbsp;</span>
</div>
<div id="DaySchedule_8amDetail">
    <span>&nbsp;</span>
</div>
<div id="DaySchedule_9amDetail">
    <span>&nbsp;</span>
</div>
<div id="DaySchedule_10amDetail" class="end"> <-- end
    <span>&nbsp;</span>
</div>
<div id="DaySchedule_11amDetail">
    <span>&nbsp;</span>
</div>

I am trying to have jquery wrap elements from class start to class end in a div

I have tried many different things and looked through stackoverflow.

$('div.start').each(function(){
   $(this).nextUntil('div.end').wrap(document.createElement('div'));
});

This from what I have found should work but it does nothing. It doesn't even create a div

$("div.start").wrapAll("<div>");

this creates a div around only the element with class start I want to extend it till class end.

Is there a clear way to do this? Should I not even bother with wrap or wrapAll? Is there a way to inject an open div tag before an element with a certain class and add a closing tag after an element with a certain class (start and end). I have tried preappend and append with no luck.

Any help would be greatly appreciated. Thank you.

Edit: --------------------------------------------------------

The selected answer pretty much worked for me with some little manipulation so here is the code that worked for me:

  $('.start').each(function(){
    var $nextGroup = $(this).nextUntil('.end').add(this);
    $nextGroup.add($nextGroup.next()).wrapAll('<div class="draggableStuff">');
});

Upvotes: 3

Views: 1403

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You were pretty close.... you do want wrapAll() but using the nextUntil() concept you have.

$('.start').each(function(){
    $(this).nextUntil('.end').wrapAll('<div class="wrapper">');
});

DEMO

If you need to also wrap the start and end use add() to add the start and end elements:

$('.start').each(function(){
     var $nextGroup= $(this).nextUntil('.end')
     $nextGroup.add(this).add($nextGroup.next()).wrapAll('<div class="wrapper">');
});

DEMO 2

Upvotes: 4

Related Questions