Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - Display only 15 list items in a UL

Tags:

html

jquery

I have a list that is generated by WordPress and I there is no way to limit how many tags to display through the function it self.

With jQuery I decided to do this to display only the first 15:

$j(function(){
    if( $j('#popular-tags').length > 0 ){
        var displayAmt = 15;

        var list = $j(this).find('ul');
        for(var i=1; i <= displayAmt; i++ ){
            ....
        }
    }
});

I'm a bit lost on how to iterate through each list item. But i have a class called .not-display that I want to add to the respective list item. I also wasn't sure if I need to use the .each() function that jQuery provides.

Can someone enlighten me?

like image 883
chasethesunnn Avatar asked Nov 30 '25 01:11

chasethesunnn


2 Answers

You'll find that most of the time, a loop is not necessary with jQuery:

var displayAmt = 15;
$j('#popular-tags li').slice(displayAmt).hide();

This code finds all the li elements within the #popular-tags div, uses slice() to get every element after the 15th element, and calls hide() on them all. You can also choose to call remove() instead if you wish.

like image 88
David Tang Avatar answered Dec 02 '25 13:12

David Tang


I would suggest using the lt selector, which takes a zero-based index:

$("ul > li:lt(15)").show();
like image 33
karim79 Avatar answered Dec 02 '25 15:12

karim79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!