如何在jQuery中包装具有不同类名的DIV标签?

Max*_*Max 3 javascript jquery dom parent-child jquery-traversing

可能重复:
如何将父元素添加到一组段落中?

我在文档中重复了以下HTML块

<!-- first block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

<!-- second block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

...
Run Code Online (Sandbox Code Playgroud)

如何用jQuery包装Divs以获得这样的结果HTML ...

<!-- first block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

<!-- second block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

...
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 17

你很幸运,这正是wrapAll为了:

$(".first, .second").wrapAll('<div class="container"></div>');
Run Code Online (Sandbox Code Playgroud)

实例 | 资源


您的编辑显着改变了问题.如果只需要某个包含块中执行上述操作,则可以遍历包含块并wrapAll仅应用于其内容.您需要一种方法来确定您想要对div进行分组的方式,这些方法尚未在问题中指定.

如果div周围有某种容器,你可以这样做:

$(".block").each(function() {
  $(this).find(".first, .second").wrapAll('<div class="container"></div>');
});
Run Code Online (Sandbox Code Playgroud)

在那个例子中,我假设div在类的容器中"block".

实例 | 资源

如果没有结构方法来识别它们,你将不得不以其他方式做到这一点.例如,在这里我们通过假设任何时候看到a来做first,我们应该停止分组:

var current = $();

$(".first, .second").each(function() {
  var $this = $(this);
  if ($this.hasClass('first')) {
    doTheWrap(current);
    current = $();
  }
  current = current.add(this);
});
doTheWrap(current);

function doTheWrap(d) {
  d.wrapAll('<div class="container"></div>');
}
Run Code Online (Sandbox Code Playgroud)

实例 | 资源

这样做是因为$()文档顺序给你元素,所以如果我们按顺序遍历它们,保存它们,然后在我们看到一个新的时候first(当然,最后清理)结束之前的那些,你得到期望的结果.

或者这是另一种做同样事情的方法,它不使用wrapAll.它依赖于第一个匹配元素是a first(所以seconds之前没有firsts!):

var current;

$(".first, .second").each(function() {
  var $this = $(this);
  if ($this.hasClass('first')) {
    current = $('<div class="container"></div>').insertBefore(this);
  }
  current.append(this);
});
Run Code Online (Sandbox Code Playgroud)

实例 | 资源