Categories
JavaScript Answers

How to hide and show list items after the nth item with jQuery?

Spread the love

Sometimes, we want to hide and show list items after the nth item with jQuery.

In this article, we’ll look at how to hide and show list items after the nth item with jQuery.

How to hide and show list items after the nth item with jQuery?

To hide and show list items after the nth item with jQuery, we can select the element after the nth item wit the gt selector and call show on them.

For instance, we write:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>

<button class='showButton'>
  show
</button>

to add a button and a list.

Then we write:

$('ul li:gt(3)').hide();
$('.showButton').click(() => {
  $('ul li:gt(3)').show();
});

We select the li’s in the ul element that’s after the 3rd item with $('ul li:gt(3)').

Then we call hide on them to hide them.

And then we select the button with $('.showButton') and then call click on it with a callback that calls $('ul li:gt(3)').show(); to show the li’s after the 3rd item.

Conclusion

To hide and show list items after the nth item with jQuery, we can select the element after the nth item wit the gt selector and call show on them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *