tags:

views:

456

answers:

3

Hi all,

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!

+3  A: 

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);
sighohwell
Oh! I always forget about slice() -- nice reminder!
artlung
+2  A: 

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>
artlung
special thanks to you
Baha
glad to help Baha.
artlung
A: 

thank you guys! you saved my day.

Baha
So you can "accept" an answer, which marks it in green. To give specific thanks you can add it to an individual answer, or for more general thanks you can edit and update your question. Glad to help!
artlung