Wrap/Break List Items In Two Ul
Trying to Wrap/Break list items and add class by replace text from list items, example below? Original Html:
Solution 1:
Here's one solution, moving the LI's to new parents, based on the text in .label
var widget = $('.widget-content'),
ul = widget.find('ul'),
classes = ['left', 'right'];
ul.find('li').each(function() {
var span = $(this).find('.label');
var text = span.text();
var parent = widget.find('[data-parent="'+text+'"]');
if ( parent.length === 0 ) {
widget.append( $('<ul class="'+classes.shift()+'" data-parent="'+text+'" />').append(this) )
} else {
parent.append(this)
}
ul.remove();
});
.left {color: green}
.right {color: blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-content">
<ul>
<li><span class="label">textone</span> Test Content</li>
<li><span class="label">texttwo</span> Test Content</li>
<li><span class="label">texttwo</span> Test Content</li>
<li><span class="label">texttwo</span> Test Content</li>
<li><span class="label">textone</span> Test Content</li>
<li><span class="label">textone</span> Test Content</li>
</ul>
</div>
Solution 2:
Following your code (same principle), this is another solution:
var $widget = $('.widget-content');
var elements = {};
$widget.find('li').each(function () {
var key = $(this).find('span').text();
// If key is not defined yet, we define an Array
elements[key] = typeof elements[key] === 'undefined' ? [] : elements[key];
// Adds the content of the <li>
elements[key].push($(this).text());
}).parent().remove(); // Clears the <ul>
$.each(elements, function(index, values) {
var $ul = $('<ul/>').addClass(index);
$.each(values, function () {
$ul.append($('<li/>').text(this));
});
$widget.append($ul);
});
.textone {
color: red;
}
.texttwo {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-content">
<ul>
<li><span class="label">textone</span> Test Content</li>
<li><span class="label">texttwo</span> Test Content</li>
<li><span class="label">texttwo</span> Test Content</li>
<li><span class="label">texttwo</span> Test Content</li>
<li><span class="label">textone</span> Test Content</li>
<li><span class="label">textone</span> Test Content</li>
</ul>
</div>
Solution 3:
jquery wrapAll()
is another short & sweet way.
// get unique texts
var uniTxt = [];
$('.label').text(function(index,txt){
( $.inArray(txt,uniTxt) > -1) ? null : uniTxt.push( txt ) ;
});
// rearrange items
$(uniTxt).each(function(index, className){
$('li').filter(':contains('+className+')')
.unwrap() // remove initial parent ul
.wrapAll('<ul class='+className+'>'); // wraps similar txt with a Ul & add class
});
Post a Comment for "Wrap/Break List Items In Two Ul"