如何使用jquery包装每个div?

时间:2017-09-14 13:26:35

标签: jquery

我试图将每个.test1和.test2类包装成一个div标签,但它包装整个div类。请建议。

HTML

<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>

的例外:

<div class="container">
    <div class="test1">This is demo paragraph1.</div>
    <div class="test2">This is demo paragraph2.</div>
</div>
<div class="container">
    <div class="test1">This is demo paragraph1.</div>
    <div class="test2">This is demo paragraph2.</div>
</div>
<div class="container">
    <div class="test1">This is demo paragraph1.</div>
    <div class="test2">This is demo paragraph2.</div>
</div>

Jquery:

$(".test1, .test2").wrapAll("<div class="container"></div>");

2 个答案:

答案 0 :(得分:1)

  1. jQuery("<div class="container"></div>")中的引号导致错误。
  2. 请务必在document ready function
  3. 中运行此操作
  4. 澄清的期望有点棘手,但可以假设总是有两个组,使用addBack函数。
  5. This Fiddle根据上述假设显示了一种使其有效的方法:

    // no-conflict safe shorthand document ready
    jQuery(function($) {
      $(".test1").each(function() {
          $(this).next(".test2").addBack().wrapAll('<div class="container"></div>');
      });
    });
    

答案 1 :(得分:1)

你可以这样,使用CSS adjacent sibling combinator (+)进行快速选择:

&#13;
&#13;
$('.test1 + .test2').each(function() {
    $(this).prev().addBack().wrapAll('<div class="container" />');
});
&#13;
.container {
    border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
&#13;
&#13;
&#13;

同样在JSFiddle

请注意,对于旧版本的jQuery,应使用addBack()而不是andSelf()方法。