开发者

How to wrap (to group) a list of elements into another element with 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&开发者_如何学Cgt;
</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.


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/


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/


.wrap() api is what you are looking for

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜