How to wrap multiple div blocks with different class names in jQuery? [duplicate]

烈酒焚心 提交于 2019-12-12 05:25:57

问题


Possible Duplicate:
How to wrap DIV tags with different class names in jQuery?

I have the following HTML blocks repeated in the document

<!-- 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>

...

How can I wrap the blocks of Divs with jQuery to get the following result...

<!-- 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>

...

回答1:


You can do something like this :

$('#btnTest').on('click', function() {
    $("body").append('<div class="container"></div>');
    $("body").append('<div class="container"></div>');

    $(".first").eq(0)
        .clone()
            .appendTo($(".container").eq(0))
            .end()
        .remove();

    $(".second").eq(0)
        .clone()
            .appendTo($(".container").eq(0))
            .end()
        .remove();

    $(".first").eq(0)
        .clone()
            .appendTo($(".container").eq(1))
            .end()
        .remove();

    $(".second").eq(0)
        .clone()
            .appendTo($(".container").eq(1))
            .end()
        .remove();
});

First you add to the DOM the number of div you want with class container. Then for each div .first and .second you have to take the first in the dom $(".first").eq(0) clone it, then append it to the first ".container". You have to use .end() before remove to make sure to remove the original div and not the cloned one.

You do this for each div and you change the ".container" by changing the number in $(".container").eq(0).

This code works fine for your example, but if you have more ".container" you should make a loop of it.



来源:https://stackoverflow.com/questions/13878539/how-to-wrap-multiple-div-blocks-with-different-class-names-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!