Wrap list items by class name

I asked the corresponding answer, but not the same as this question: How to make a new Div inside the list items
My question is how to split the list items and add a new class search from the list items, example below?

Basic HTML: Fiddle

<div class="widget-content">
<ul>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>

<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
</ul>
</div>

I want to break list items into classes as follows:

<div class="widget-content">

<ul class="label1"> <!--add class find from list-->
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
</ul>

<ul class="label2"> <!--add class find from list-->
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
</ul>

</div>

I mean the elements of the list of transitions by classes and add the class to the parent ulfind from the above example of list elements. How to do it just jQuery / JS?
Thanks in advance.

+1
source share
1 answer

jsBin demo

$(".widget-content").each(function(){

  var $li = $(this).find("li").unwrap(); // unwrap removes the old UL wrapper
  var uniq = [];

  // Create a collection of unique "label*" classes:
  $li.find("[class^=label]").attr("class", function(i, v){
    if(!~$.inArray(v, uniq)) uniq.push(v);
  });

  // Group LI by A class, and wrap into a new UL with the same class
  $.each(uniq, function(i, klas){
    $("a."+klas).closest("li").wrapAll($("<ul/>",{class:klas}));
  });

});
+2

All Articles