Reputation:
Can somebody help me convert the following html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
into this one
<ul>
<li class="li_group">
<ul>
<li>1</li>
<li>2</li>
</ul>
</li>
<li class="li_group">
<ul>
<li>3</li>
<li>4</li>
</ul>
</li>
</ul
using jQuery?
Thank you!
Upvotes: 0
Views: 2482
Reputation: 51
Here is my solution :
Jquery function :
jQuery.fn.groupListElement = function() {
var $list = $(this[0]);
var args = arguments[0] || {};
var groupClassName = args.groupClassName || 'li_group';
var size = args.size || 2;
if ( $list.length > 0 ) {
var wrapper = '<li class="' + groupClassName + '"><ul></ul></li>';
while ( $('> li[class!="' + groupClassName + '"]',$list).slice(0, size).length >= 1) {
$('> li[class!="' + groupClassName + '"]',$list).slice(0, size)
.wrapAll(wrapper);
}
}
return $list;
};
Call to the function
$('ul').groupListElement({groupClassName: 'li_group', size : 3});
Use with Jquery Cycle :
$('ul')
.groupListElement({groupClassName: 'li_group', size : 3})
.cycle();
Enjoy !
Upvotes: 0
Reputation: 33813
I'm guessing that you may end up needing to do this for a different number of items. My solution includes a while loop. Adjust the number in the while() condition, and in the selector for the :lt(2) to capture a different number of list items.
<ul id="divide">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script type="text/javascript">
while ($('ul#divide > li[class!="li_group"]:lt(2)').length >= 1) {
$('ul#divide > li[class!="li_group"]:lt(2)')
.wrapAll('<li class="li_group"><ul></ul></li>');
}
</script>
While debugging I used this CSS to assure I was producing the right HTML.
<style type="text/css">
ul { border: 1px solid #f00; }
.li_group { border: 1px solid #00f; }
</style>
Upvotes: 1
Reputation: 8755
The following should do the trick...
var $liWrapper = $("<li class='li_group'><ul></ul></li>");
$("li").slice(0,2).wrapAll($liWrapper)
.end()
.slice(2,4).wrapAll($liWrapper);
Upvotes: 2