Wrap every 3 divs in a div

前端 未结 6 1952
执念已碎
执念已碎 2020-11-22 09:03

Is it possible to use nth-child selectors to wrap 3 divs using .wrapAll? I can\'t seem to work out the correct equation.

so...



        
6条回答
  •  借酒劲吻你
    2020-11-22 09:43

    Here is a more usable version of Nick's above:

    window.WrapMatch = function(sel, count, className){
      for(var i = 0; i < sel.length; i+=count) {
        sel.slice(i, i+count).wrapAll('
    '); } }

    You would use this like:

    var ele = $('#menu > ul > li'); 
    window.WrapMatch(ele, 5, 'new-class-name');
    

    window should be replaced with your Handlers namespace, of course.

    Updated: A slightly better version that leverages jQuery

    (function($){
      $.fn.wrapMatch = function(count, className) {
        var length = this.length;
        for(var i = 0; i < length ; i+=count) {
          this.slice(i, i+count).wrapAll('
    '); } return this; }; })(jQuery);

    Use like:

    $('.list-parent li').wrapMatch(5,'newclass');
    

    The second parameter for the wrapper name is optional.

提交回复
热议问题