jQuery group list items by class -


i have unordered dynamic list same class list items. , want group same class list items 1 ul in main ul. how can group same class list items?

i want convert below dynamic list

<ul>     <li class="a1">some content</li>     <li class="a1">some content</li>     <li class="a1">some content</li>     <li class="a1">some content</li>     <li class="a2">some content</li>     <li class="a2">some content</li>     <li class="a3">some content</li> </ul> 

into this

<ul>     <li>a1         <ul>             <li class="a1">some content</li>             <li class="a1">some content</li>             <li class="a1">some content</li>             <li class="a1">some content</li>         </ul>     </li>     <li>a2         <ul>             <li class="a2">some content</li>             <li class="a2">some content</li>         </ul>     </li>     <li>a3         <ul>             <li class="a3">some content</li>         </ul>     </li> </ul> 

here solution you:

html:

<ul id="basenode">     <li class="a1">a</li>     <li class="a1">b</li>     <li class="a1">c</li>     <li class="a1">d</li>     <li class="a2">e</li>     <li class="a2">f</li>     <li class="a3">g</li> </ul> 

jquery:

$(document).ready(function(){     var lis = $("#basenode > li");     var = { };      $.each(lis, function(i, el){         var c = $(el).attr("class");          if(as[c] == null) {             as[c] = new array();         }          as[c].push(el);     });      $("#basenode").empty();     $.each(as, function(i, el) {         var li = $("<li>" + i.touppercase() + "</li>");         var ul = $("<ul></ul>");          $(ul).append(el);         $(li).append(ul);         $("#basenode").append(li);     }); }); 

i created jsfiddle can see result. added id first ul convenience.


Comments