I would like to achieve the following:
If there are more than 12 li's within a given ul, replace the last one with "..." and hide any that appear after the 12th one.
Can anyone throw some pointers my way?
I would like to achieve the following:
If there are more than 12 li's within a given ul, replace the last one with "..." and hide any that appear after the 12th one.
Can anyone throw some pointers my way?
<ul data-truncate="12">
jQuery:
$('[data-truncate]').each(function(){
var n = $(this).data('truncate') -1;
$('li', this).eq( n ).nextAll().hide().last().after('<li>...</li>');
});
you can simply use jQuery .slice()
$('ul').html($('ul li').slice(0,12)).append("..");
see this fiddle
Try this:
$('#myList > li:eq(11)').nextAll().hide().end().after('<li>...</li>');
Note that the supplied index in eq()
method is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree. Hence, eq(11)
means the item 12 here.
here is the working fiddle: http://jsfiddle.net/acturbo/w3yep/7/
sample html:
<ul id="mylist">
<li>1 </li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5 last one to see</li>
<li>6 will be truncated</li>
<li>7 will be truncated</li>
<li>8 will be truncated </li>
</ul>
jquery:
$(document).ready(function () {
var maxToShow = 5;
$("#mylist li").each( function(i, e){
// truncate all li elements after the 5th
if ( i >= maxToShow){
// $(e).remove(); // remove it
$(e).hide(); // or hide it
}
});
});