如何用不同的类名包装DIV标签? [重复]

问题描述 投票:3回答:2

重复: 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>

...
javascript jquery dom parent-child jquery-traversing
2个回答
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(所以在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);
});

Live Example | Source


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

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

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

更好。

© www.soinside.com 2019 - 2024. All rights reserved.