Wrap a <ul> around every 6 <li> with jQuery
I would like to use jQuery to wrap <ul class="main-list">
around each of the 6 first children <li>
. What's the best way to accomplish this with jQuery?
Here's the jQuery I'm using:
$(document).ready(function() {
var lis = $(".main-list li");
for(var i = 0; i < lis.length; i+=6) {
lis.slice(i, i+6)
.wrapAll("<ul class='list_unstyled'></ul>");
}
});
Here's the source code (ExpressionEngine):
<ul class="list-unstyled main-list">
{exp:channel:category_archive channel="speakers" style="linear" backspace="7"}
<li>
{categories}
<a href="#">{category_name}</a>
{/categories}
{entry_titles}
<ul class="list-unstyled">
<li><a href="{path='site/speaker'}">{title}</a></li>
</ul>
{/entry_titles}
</li>
{/exp:channel:category_archive}
</ul>
Here's the code that is currently being output with jquery above:
<ul class="list-unstyled main-list">
<ul class="list_unstyled">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<ul class="list_unstyled">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</ul>
Here's the desired output after jQuery implementation:
<ul class="list_unstyled">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<ul class="list_unstyled">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
source to share
your jquery function already does what you wanted to group them by 6, so you just need to remove the .main-list that will wrap your list. all you have to do is unwrap after the loop.
$('.main-list>ul').unwrap();
i.e.
$(document).ready(function() {
var lis = $(".main-list li");
for(var i = 0; i < lis.length; i+=6) {
lis.slice(i, i+6)
.wrapAll("<ul class='list_unstyled'></ul>");
}
$('.main-list>ul').unwrap();
});
source to share
I think something like this:
function wrapLi( parent ){
var numChildren = $( parent ).children( 'li' ).length,
wrappers = [];
for( var i = 0; i < numChildren / 6; i++ ){
wrappers[i] = $( '<ul class="main-list"></ul>' );
// the meat and potatoes... select the first six elements of the matched set
// check out http://www.w3schools.com/jquery/jquery_ref_selectors.asp
wrappers[i].append( $( parent ).children( 'li:lt(6)' ) );
}
return wrappers; // the array of <ul> that you can put wherever you want
}
var stuff = wrapLi( $( '.main-list' ) );
$( 'body' ).append( stuff );
Also, there is a violin here where you can master it. http://jsfiddle.net/nfw0kpxt/
source to share
You have a JsFiddle here
It's very easy to decide.
var firstUl = $("<ul>");
var secondUl = $("<ul>");
var size = $(".main-list li").size();
var elements = $(".main-list li");
size--;
for(var i = 0; i < size; i++) {
firstUl.append(elements[i]);
}
secondUl.append(elements[size++]);
$(".result").append(firstUl);
$(".result").append(secondUl);
source to share