How can I get first 4 of the childrens and wrap it into the div?

余生长醉 提交于 2020-02-03 10:20:48

问题


How can I find first 4 children of the parent and wrap it into div, then next 4 and so on? Google does not know! :(

FROM:

<div class="main">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
</div>

TO:

<div lass="main">
    <div class="pack1">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
    </div>

    <div class="pack1">
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <div>8</div>
    </div>
</div>

Any help much appreciated.

I can find first 4 by: $('.main > div:lt(4)').wrapAll('<div class="pack1"></div>'); But how to get every 4??

Pete


回答1:


Not the most elegant way but its working.

var sel;
while ( (sel = $('.main > div:not(.pack1)')).length > 0 )
{
    sel.slice(0,4).wrapAll('<div class="pack1"></div>');
}

Here a fiddle.

Update

Here with counter for the class. We have to use a 2nd class pack for the exclude of all packed divs.

var sel;
var count = 1;
while ( (sel = $('.main > div:not(.pack)')).length > 0 )
{
    sel.slice(0,4).wrapAll('<div class="pack pack'+ count++ +'"></div>');
}

And the fiddle

Or we go with

var sel;
var count = 1;
while ( (sel = $('.main > div:not([class^="pack"])')).length > 0 )
{
    sel.slice(0,4).wrapAll('<div class="pack'+ count++ +'"></div>');
}

fiddle for that.




回答2:


this is just an idea ( and im not sure i coded it right ), but you could use this method.

   var first = $(".main div:lt(4)");
    $(".main div:lt(4)").remove();
    var second = $(".main div:lt(4)");
    $(".main div:lt(4)").remove();

    $(".main").append("<div class=pack1>" + first+ "</div>");
    $(".main").append("<div class=pack2>" + second+ "</div>");


来源:https://stackoverflow.com/questions/6490950/how-can-i-get-first-4-of-the-childrens-and-wrap-it-into-the-div

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