jQuery’s Greater and Less Than Selectors

Today I learned about jQuery’s greater than selector, :gt().

The :gt() selector selects elements with an index number higher than a specified number. The index numbers start at 0.

I’m using this selector to hide more than 10 recent posts on my TIL page. Each of these posts is inside a list item (li) and a child of the unordered list (ul) with a class called “recent”. I then added a toggle function on a button to show them again by using the same selector.

Example:

$(document).ready(function(){   $("ul.recent").find("li:gt(9)").hide();   $("ul.recent").has("li:nth-child(10)").after(""showhide button" >Show/Hide all TIL posts");   $("a.showhide").click(function() {     $("ul.recent").find("li:gt(9)").toggle("slow");     $   }); }); 

There is also a less than selector in jQuery. It works similarly, except that it selects elements with an index number lower than the specified number. Syntax: :lt()

Note: Since I’m using a Jekyll site and generating that TIL list via Liquid, another solution is to set a counter after which it automatically adds a class directly to the HTML to hide those items that we can then toggle later. I think the jQuery solution is cleaner, though.



Comments

Leave a Reply

Webmentions

If you've written a response on your own site, you can enter that post's URL to reply with a Webmention.

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.