Wrap every 2 divs in an each loop inside a div

Client is using visual composer to create a grid of elements, hes got 3 rows, with 4 colums each, and hes going to be adding more rows in the future, so he wants me to create a slider that only displays 2 rows with 4 columns on each slide (responsive to only display 1 column on mobile, buts thats another story)

Anyways, im using an each loop, to grab all the divs from the 3 rows, and insert them into a single slider div. The part im having trouble with is wrapping every 2 divs into one div to create the two rows, then i would float each of those, to create the 4 columns.

Heres what i have so far

    $.each( $('.slidergrid'), function(i, left) {
    count = 0;
   $('.wf-span-3', left).each(function() {
        var content = $(this).html();

        if (count == 1) {
            $('#slider').append(content+'</div>');

            alert(count);
            count = 0;
        } else {

            $('#slider').append('<div style="border:1px solid #ccc">'+content);

            alert(count);
            count = count + 1;
        }

   });
})

Not the most fancy solution, but i tried using a slice function i found here, and keep getting an uncaught error that slice is not defined or something like that. .slidergrid is the class i added to the visual composer rows to be able to target them. and #slider is the slideshow div that.

The above code for some reason outputs one element inside the border, on div outside the border, one div inside, one div outside, etc. When im expecting it two output 2 divs inside the border at a time

Any help would be appreciated.

Heres a Jsfiddle https://jsfiddle.net/Ldh2v1nj/

i was sorta able to find a solution, but its not the cleanest code, and requires two loops… any chance someone here could refactor it for me?

function grabElements(){
	$.each( $('.slidergrid'), function(i, left) {
	
	   $('.wf-span-3', left).each(function() {
			var content = $(this).html();
			$('#slider').append('<div class="slideshow_item" >'+content+'</div>');	
	   });
	})
}
function wrapElements(){
		var divs = $("#slider > .slideshow_item");
		for(var i = 0; i < divs.length; i+=2) {
		  divs.slice(i, i+2).wrapAll("<div style='width:23%; padding:1%; float:left;'></div>");
		}
}
$.when($.ajax(grabElements())).then(function () {
		wrapElements()
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.