jQuery's Greater and Less Than Selectors

July 6, 2016
Category: TIL
Tags: Javascript

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("<a class=\"showhide button\" >Show/Hide all TIL posts</a>");
  $("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.

Find this post useful?

Buy me a coffeeBuy me a coffee