Instead of showing and hiding each element separately, you can add a class to li elements after the first three, and then use CSS to show and hide them by adding the class to the parent ul element:
JavaScript:
$(function(){ $('.filter_item ul') .addClass('hidemore') .each(function(){ $(this).find('li:gt(2)').addClass('more'); }) .append($('<li/>').append($('<a/>').attr('href','javascript:void(0)').text('more...'))) .find('a').toggle(function(){ $(this).text('less...').closest('ul').removeClass('hidemore'); },function(){ $(this).text('more...').closest('ul').addClass('hidemore'); }); });
CSS
.filter_item ul.hidemore li.more { display: none; }
Notes:
The href attribute with javascript:void(0) added to the links so that they appear as links but do not move anywhere. Therefore, click handlers should not stop the event.
.find('a') after adding elements occurs because it does not work to add click event handlers to elements until they are added to the page. (If the text in the lists also contains links, you need to add a class to the added links so that they can be targeted specifically at this stage.)
Guffa source share