Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap (to group) a list of elements into another element with jquery?

Tags:

jquery

I have the following structure.

<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>

Can I convert it into:

<uL>
    <li></li>
    <li></li>
    <li></li>
</ul
<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

So the task is to group li into "rows". There are always 3 li in 1 row, but row number is always different.

Does someone know, how to do this? Thanks.

like image 729
Arsen K. Avatar asked Jun 23 '11 09:06

Arsen K.


3 Answers

You can do it with wrapAll:

var a = $('li');
do $(a.slice(0,3)).wrapAll('<ul />');   
while((a = a.slice(3)).length>0)

example: http://jsfiddle.net/niklasvh/mZr4h/

like image 89
Niklas Avatar answered Sep 28 '22 04:09

Niklas


var i, num = 3, $ul = $('#ul'), $li = $('#ul > li');
for (i=0;i<$li.length;i+=num) {
    $li.slice(i,i+num).wrapAll('<ul />');
}
$ul.find('> ul').unwrap();

http://jsfiddle.net/Q2bYz/

like image 25
sod Avatar answered Sep 28 '22 03:09

sod


.wrap() api is what you are looking for

like image 30
Abdul Kader Avatar answered Sep 28 '22 04:09

Abdul Kader