Skip to content
Advertisement

Hide items from two or more lists with the same class name

I’ve got two lists with the same class name which show only the first 4 items. When either of the ‘more’ button below them is clicked, I wish to reveal the rest of the items for both lists. This behaviour works fine. Only problem is that the following line: $('.feature-list li:gt(3)').hide(); shows the first 4 items for only the first list and not the second. Any way I can target both lists?

$('.feature-list li:gt(3)').hide();
$('.more-btn').click(function() {
    $('.feature-list li:gt(3)').show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>List 1</p>
<ul class="feature-list feature-p-list1">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
  <li>Item 10</li>
</ul>
<button class="more-btn">Show More</button>

<p>List 2</p>
<ul class="feature-list feature-p-list2">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
  <li>Item 10</li>
</ul>
<button class="more-btn">Show More</button>

Advertisement

Answer

You can use find method to find li under each list. Otherwise, it will all consider as a single array.

Bonus:

Fixed the problem on clicking the Show more button for individual lists. Cheer!

$('.feature-list').find('li:gt(3)').hide()
$('.more-btn').click(function() {
  $(this).parent().find('.feature-list li:gt(3)').show();
    //$('.feature-list li:gt(3)').show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <p>List 1</p>
  <ul class="feature-list feature-p-list1">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
    <li>Item 9</li>
    <li>Item 10</li>
  </ul>
  <button class="more-btn">Show More</button>
</section>

<section>
  <p>List 2</p>
  <ul class="feature-list feature-p-list2">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
    <li>Item 9</li>
    <li>Item 10</li>
  </ul>
  <button class="more-btn">Show More</button>
</section>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement