开发者

jQuery - Wrap div to multiple element

Hi

Suppose I have the code below:

  <div class="Hello">
    <div class="inner">Hello</div>
  </div>
  <div class="Goodbye">
    <div class="inner">Goodbye</div>
  </div>
  <div class="Goodnight">
    <div class="inner">Goodnight</div>
  </div>

How can I wrap a div to these 3 div? The result should be:

  <div>
      <div class="Hello">
        <div class="inner">Hello</div>
      </div>
      <div class="Goodbye">
        <div class="inner">Goodbye</div>
      </div>
      <div class="Goodnight">
        <div class="inner">Goodnight</div>
      </div>
  </div>

Update(not work)

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

<div class="Hello">
  <div class="inner">Hello</div>
</div>
<div class="Goodbye">
  <div class="inner">Goodbye</div>
</div>
<div class="Goodnight">
  <div class="inner">Goodnight</div>
</div>

<script>
$("<div>").insertBefore(".Hello").append(".Hello, .Goodbye, .Goodnight");   
</script>

Updated 2(work)

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

<div class="Hello">
  <div class="inner">Hello</div>
</div>
<div class="Goodbye">
  <div class="inner">Goodbye</div>
</div>
<div class="Goodnight">
  <div class="inner">Goodnight</div>
</div>

<script>
$("<div>").insertBefore(".Hello").append($('.Hello'), $('.Goodbye'), $('.Goodnight'));  
</script>

Updated 3(not work)

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

<div class="Hello">
  <div class="inner">Hello</div>
</div>
<div class="开发者_高级运维Goodbye">
  <div class="inner">Goodbye</div>
</div>
<div class="Goodnight">
  <div class="inner">Goodnight</div>
</div>

<script>
//$("<div>").insertBefore(".Hello").append($('.Hello'), $('.Goodbye'), $('.Goodnight'));    
$(".Hello, .Goodbye, .Goodnight").wrap('div');
</script>

Result:

<div class="Hello">
  <div class="inner">Hello</div>
<div class="Hello">
  <div class="inner">Hello</div>
</div></div>
<div class="Hello">
  <div class="inner">Hello</div>
<div class="Hello">
  <div class="inner">Hello</div>
</div><div class="Goodbye">
  <div class="inner">Goodbye</div>
</div></div>
<div class="Hello">
  <div class="inner">Hello</div>
<div class="Hello">
  <div class="inner">Hello</div>
</div><div class="Goodnight">
  <div class="inner">Goodnight</div>
</div></div>

Thank you


Don't use the .wrap() method. Just create a new div and .append() each element. E.g:

$("<div>")
    .insertBefore(".Hello")
    .append($(".Hello, .Goodbye, .Goodnight"));

The divs will be moved inside, not cloned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜