Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to split every 2 li's and append them to a div

Tags:

jquery

I have a generic list

 <ul>
    <li>list item1</li>
    <li>list item2</li>
    <li>list item3</li>
    <li>list item4</li>
    <li>list item5</li>
   <li>list item6</li>
</ul>

But what I want to do is

<div class="list">
<ul>
    <li>list item1</li>
    <li>list item2</li>
 </ul>
</div>

<div class="list">
<ul>
    <li>list item3</li>
    <li>list item4</li>
 </ul>
</div>

<div class="list">
<ul>
    <li>list item5</li>
    <li>list item6</li>
 </ul>
</div>

The reason I can't add classes to the li's is that this is a dynamic menu created in Business Catalyst, I could use any advice as to the best way to deal with this situation.

Best Tara

like image 415
Tara Irvine Avatar asked Jan 26 '11 15:01

Tara Irvine


1 Answers

Example: http://jsfiddle.net/jBYqt/2/

$('ul > li:nth-child(2n-1)').each(function() {
    $(this).next().add(this).wrapAll('<div class="list"><ul></ul></div>');
}).eq(0).closest('div').unwrap();
  • nth-child-selector(docs) gets every second <li> starting with the first
  • each()(docs) iterates over them
  • next()(docs) gets the next <li>
  • add()(docs) adds the current one to the next (so you have groups of 1&2, 3&4, etc.)
  • wrapAll()(docs) wraps them with the new wrappers.
  • eq()(docs) gets the first one from the set
  • closest()(docs) traverses up to the closest (newly created) <div> ancestor
  • unwrap()(docs) removes the old <ul>

EDIT: Modified my answer to deal with an odd number of <li> elements.

like image 141
user113716 Avatar answered Oct 09 '22 11:10

user113716