问题
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> </span>
</div>
<div id="DaySchedule_6amDetail">
<span> </span>
</div>
<div id="DaySchedule_7amDetail" class="start"> <-- start
<span> </span>
</div>
<div id="DaySchedule_8amDetail">
<span> </span>
</div>
<div id="DaySchedule_9amDetail">
<span> </span>
</div>
<div id="DaySchedule_10amDetail" class="end"> <-- end
<span> </span>
</div>
<div id="DaySchedule_11amDetail">
<span> </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