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

家住魔仙堡 提交于 2020-01-04 01:52:05

问题


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">');
});

回答1:


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



来源:https://stackoverflow.com/questions/25814935/in-jquery-how-can-i-wrap-multiple-elements-with-a-div-given-that-i-have-a-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!