如何用不同的类名包装DIV标签?

时间:2012-12-14 11:24:28

标签: javascript jquery dom parent-child jquery-traversing

  

重复:
  How can I add a parent element to a group of paragraph?

我在文档中重复了以下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>

...

如何使用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>

...

2 个答案:

答案 0 :(得分:17)

你很幸运,这正是wrapAll的用途:

$(".first, .second").wrapAll('<div class="container"></div>');

Live Example | Source


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

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

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

在该示例中,我假设div位于具有类"block"的容器中。

Live Example | Source

如果没有结构方法来识别它们,你将不得不以其他方式做到这一点。例如,我们在这里假设我们看到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>');
}

Live Example | Source

这是有效的,因为$()为您提供了文档顺序中的元素,因此如果我们按顺序循环遍历它们,将它们保存起来,然后在我们看到时将它们包起来新的first(当然,最后清理),你得到了理想的结果。

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

var current;

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

Live Example | Source

答案 1 :(得分:3)

$('div').wrapAll('<div class="container" />');

会这样做,但也可以包装任何其他div:

$('.first, .second').wrapAll('<div class="container" />'); 

更好。