jQuery wrap code after x number of elements

后端 未结 4 1299
情话喂你
情话喂你 2020-12-09 00:51

I have a UL that contain any number of LIs. I am trying to create some jQuery code that will parse the original UL and wrap a UL and another LI after every 5 of the original

相关标签:
4条回答
  • 2020-12-09 01:02

    You can use a loop.

    For example: (Untested)

    while($('ul#original li').length) {
        var newContainer = $('<li class="new_wrap_li"><ul class="new_wrap_ul" /></li>')
            .appendTo('#processed_ul');
    
    
        $('ul#original li:lt(4)').detach().appendTo(newContainer.children('ul'));
    }
    
    0 讨论(0)
  • 2020-12-09 01:16

    Something like this will do it:

    $('#original_ul').find('li:nth-child(5n)').each(function(){
        $(this).prevAll('li').andSelf()
            .wrapAll('<ul class="new_wrap_ul"></ul>');
    }).end().find('ul').wrap('<li class="new_wrap_li"></li>')
    .find('li:first-child').addClass('original_li');
    
    0 讨论(0)
  • 2020-12-09 01:22

    You can do this:

    var lis = $("#original_ul li");
    for(var i = 0; i < lis.length; i+=5) {
      lis.slice(i, i+5)
         .wrapAll("<li class='new_wrap_li'><ul class='new_wrap_ul'></ul></li>");
    }
    

    This keeps them in the same #original_ul element, but you could just change the ID if that's necessary. This approach generates the exact output html you have in the question aside from the ID on the top <ul>

    0 讨论(0)
  • 2020-12-09 01:24
    jQuery('ul#original_ul').attr('id', 'processed_ul')
        .find('li:nth-child(5n)').each(function() {
            $(this).prevAll('li').andSelf()
                .wrapAll('<li class="new_wrap_li"><ul class="new_wrap_ul"></ul></li>');
        });
    
    0 讨论(0)
提交回复
热议问题