How To Dynamically Group Every N-divs And Wrap Up With A New Div In Jquery?
I want to select every 4 divs with class 'contents' and wrap it in another new div that is created dynamically using Jquery. my HTML is as follows;
Solution 2:
var sel;
var count = 1;
while ((sel = $('#postings > div.contents')).length > 0) {
sel.slice(0, 4).wrapAll('<div class= "test" id="newDivforWraping' + count+++'"></div>');
}
Solution 3:
Hope this helps: code
jQuery.fn.outerHTML = function() {
returnjQuery('<div />').append(this.eq(0).clone()).html();
};
wrappings = [];
elems = 0; // from 1 to 4
count = 0;
$.each($('div.contents'), function (index, elem) {
if (elems == 4) {
elems = 0;
count++;
}
console.log('count:' + count);
if (! wrappings[count]) {
wrappings[count] = []
}
wrappings[count].push($(elem).outerHTML());
elems++;
});
console.log(wrappings);
$.each(wrappings, function (index, w) {
wrappings[index] = w.join('');
});
bigHTML = '';
$.each(wrappings, function (index, w) {
bigHTML += '<div id="newWrap_' + index + '">';
bigHTML += w;
bigHTML += '</div>'
});
$('div#postings').html(bigHTML);
Post a Comment for "How To Dynamically Group Every N-divs And Wrap Up With A New Div In Jquery?"