Insert <div> for every 5 elements using Javascript

穿精又带淫゛_ 提交于 2019-11-30 09:14:52

Here's one way:

Example: http://jsfiddle.net/T6tu4/

$('div.wrapper > a').each(function(i) {
    if( i % 5 == 0 ) {
        $(this).nextAll().andSelf().slice(0,5).wrapAll('<div class="slide"></div>');
    }
});

Here's another way:

Example: http://jsfiddle.net/T6tu4/1/

var a = $('div.wrapper > a');

for( var i = 0; i < a.length; i+=5 ) {
    a.slice(i, i+5).wrapAll('<div class="slide"></div>');
}

You can just create a div for every fith element and move the links into them using the append method:

var wrapper = $('.wrapper');
var div;
$('a', wrapper).each(function(i,e){
    if (i % 5 == 0) div = $('<div/>').addClass('slide').appendTo(wrapper);
    div.append(e);
});

Demo: http://jsfiddle.net/Guffa/ybrxu/

I think this would do that:

var links = $('.wrapper').children();
for (var i = 0, len = links.length; i < len; i += 5) {
    links.slice(i, i + 5).wrapAll('<div class="slide"/>');
}

Try this:

$(function(){
    var curDiv = null;
    var mainDiv = $("div.wrapper");
    $("span", mainDiv).each(function(i, b){
        if(i%5 == 0) {
            curDiv = $("<div class='slide'/>").appendTo(mainDiv);
        }
        curDiv.append(b);
    });
});
Ahmad Alfy

You need to use jQuery slice with wrap

Check this question

Use slice() to select the element subset then wrapAll() to wrap the div around them. Here's a function that does that.

var wrapEveryN = function(n, elements, wrapper) {
   for (var i=0; i< elements.length; i+=n) {
       elements.slice(i,i+n).wrapAll(wrapper);
   }
}

wrapEveryN( 5, $(".wrapper a"), '<div class="slide"></div>' );

Demo: http://jsfiddle.net/C5cHC/

Note that the second parameter of slice may go out of bounds, but jQuery seems to handle this automatically.

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