0

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?

Kev
  • 397
  • 2
  • 7
  • 17

4 Answers4

0

LIVE DEMO

<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>');  
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

you can simply use jQuery .slice()

$('ul').html($('ul li').slice(0,12)).append("..");

see this fiddle

Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
0

Try this:

$('#myList > li:eq(11)').nextAll().hide().end().after('<li>...</li>'); 

FIDDLE

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.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

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
        }
    });

});
carrabino
  • 1,742
  • 1
  • 14
  • 17