在类之间包装一系列元素,直到它遇到另一个类

时间:2015-08-17 03:05:13

标签: jquery

我正在尝试将类“product-category”包含在类“content”之类的所有内容中。并且当它遇到类“结束”时停止包装。

鉴于标记:

<div class="product-category">
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Quae aliquid, ex enim eveniet!</p>
    <p>Eligendi similique maxime, fugiat porro.</p>
</div>
<div class="product-category">
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Quae aliquid, ex enim eveniet!</p>
    <p>Eligendi similique maxime, fugiat porro.</p>
</div>
<div class="end">
    <p>Lorem ipsum dolor sit amet.</p>
</div>

我想要的是:

<div class="content">
    <div class="product-category">
        <p>Lorem ipsum dolor sit amet.</p>
        <p>Quae aliquid, ex enim eveniet!</p>
        <p>Eligendi similique maxime, fugiat porro.</p>
    </div>
</div>  
<div class="content">
    <div class="product-category">
        <p>Lorem ipsum dolor sit amet.</p>
        <p>Quae aliquid, ex enim eveniet!</p>
        <p>Eligendi similique maxime, fugiat porro.</p>
    </div>
</div>  
<div class="end">
    <p>Lorem ipsum dolor sit amet.</p>
</div>

我使用了.nextUntil,但不知道如何结束它。

1 个答案:

答案 0 :(得分:0)

您可以使用.wrap

&#13;
&#13;
$('.product-category').wrap('<div class="content" />')
&#13;
.product-category {
  background: lightblue;
}
.content {
  border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product-category">
  <p>Lorem ipsum dolor sit amet.</p>
  <p>Quae aliquid, ex enim eveniet!</p>
  <p>Eligendi similique maxime, fugiat porro.</p>
</div>
<div class="product-category">
  <p>Lorem ipsum dolor sit amet.</p>
  <p>Quae aliquid, ex enim eveniet!</p>
  <p>Eligendi similique maxime, fugiat porro.</p>
</div>
<div class="end">
  <p>Lorem ipsum dolor sit amet.</p>
</div>
&#13;
&#13;
&#13;

如果您在product-category元素后面有end个元素,那么

$('.end').prevAll('.product-category').wrap('<div class="content" />')