jQuery获取下一组类?

r6l8ljro  于 2023-06-22  发布在  jQuery
关注(0)|答案(2)|浏览(117)

我有以下HTML喜欢

<body>
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
</body>

我想做的是从myCool开始,把它和接下来的4个类cool Package 成一个div?所以看起来

<div id="1" class="myWrapped">
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
 </div>
 <div id="2" class="myWrapped">
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
 </div>

你知道我该怎么做吗

flmtquvp

flmtquvp1#

尝试

$(".myCool").each(function(i){
  $(this).nextUntil(".myCool").andSelf().wrapAll("<div id='" + (i+1) + "' class='myWrapped'></div>");
});
gojuced7

gojuced72#

你可以这样做

jQuery("<div class='myCool'>blah</div>").appendTo('body');
for(var i=0; i<4;i++)
{
    jQuery('<div class="cool">some text</div>').appendTo('.myCool');
}

相关问题