Suppose there are several lists, within which there is a different number of elements. We need to know how many lists, and how many items in each of them. And also to limit the output of elements in lists of three, that is, when you click on a specially trained button, three more elements are displayed, if any. Tell me, please, how to implement this with jQuery?

<ul class="list"> <li class="item-1"></li> <li class="item-2"></li> <li class="item-3"></li> <li class="item-4"></li> <li class="item-5"></li> <li class="item-6"></li> <li class="item-7"></li> <li class="item-8"></li> </ul> <ul class="list"> <li class="item-1"></li> <li class="item-2"></li> <li class="item-3"></li> <li class="item-4"></li> <li class="item-5"></li> <li class="item-6"></li> </ul> <ul class="list"> <li class="item-1"></li> <li class="item-2"></li> <li class="item-3"></li> </ul> 
  • example of a DOM model at least write through правку поста - Vasily Barbashev
  • Added an example. - Alex
  • tried anything yourself? - Grundy
  • So far, nothing sensible. I'm trying to somehow access each element of the list, but it turns out to all at once. - Alex
  • Give html button code and add your answer - Maxim Bogdanov

1 answer 1

Greetings.

  1. Get the number of all lists

     $('ul.list').length 
  2. Get the number of items within lists

     $('ul.list').each(function() { $(this).find('li').length; // кол-во элементов внутри каждого списка поочередно }); 
  3. Restrict the output of items in lists of three

     $('ul.list').each(function() { $(this).find('li:gt(2)').hide(); // скрыть те элементы, индекс которых больше 2 }); 
  4. If necessary, add a button to lists where items are greater than 3

     $('ul.list').each(function() { if ($(this).find('li').length > 2) { $(this).append('<a href="#" class="btn">Показать еще</a>'); } }); 
  5. Add button click handler

     $('a.btn').click(function() { var ul = $(this).parent(); ul.find('li:hidden:lt(3)').show(); // показать еще 3 скрытых if (ul.find('li:hidden').length == 0) { // если больше скрытых нет $(this).hide(); // то скрыть кнопку } }); 
  • He gave an example of a button <a href="#" class="btn"> Show more </a>. Thank you, I was close to the decision)) did not correctly write this - Alex