SJ-B
SJ-B

Reputation: 95

Jquery Wrap first N number of elements into one New Elements and Rest N into another New Element using Slice

i am trying to wrap some elements within a div, logic goes like this if i have 10 div elements within one particular div, then first 5 elements should be wrapped within one new div, and other 5 should be wrapped in another new div. i am able to wrap first half, but second half is not getting wrapped at all. i want to do it using Slice method.

JsFiddle

http://jsfiddle.net/t9Pqt/

JS

var templateNode = $('.multirow');
var divLength = $(templateNode).find('div').length;
var divL = Math.round(divLength / 2);
$(templateNode).find('div').slice(0,divL).wrapAll('<div class="leftMost" />');

Upvotes: 0

Views: 237

Answers (1)

Tibos
Tibos

Reputation: 27833

You can use the following solution:

var templateNode = $('.multirow');
var divLength = $(templateNode).find('div').length;
var divL = Math.round(divLength / 2);
var nodes = $(templateNode).find('div'); // store all the nodes in one jQuery list
nodes.slice(0,divL).wrapAll('<div class="leftMost" />'); // wrap first half
nodes.slice(divL).wrapAll('<div class="rightMost" />'); // wrap remaining half

Upvotes: 1

Related Questions