Show/Hide li tag elements using jQuery

<ol>,<ul> and <li> html tags are very commonly used tags. But have you faced a situation, where depending on any condition, show some li elements and hide rest or vice versa? In this post, I will show you how to show/hide li tag element based on any criteria or condition using jQuery.


Let's consider that there are 2 list, First is an ordered list and second is an unordered list. The ordered list has alphabets and unordered list has name of countries. And on click of particular alphabet (from ordered list), show/hide the country names from the unordered list. To understand the problem, see the html below.
<ol id="alphabet">
  <li><a class="letter" href="#">A</a></li>
  <li><a class="letter" href="#">B</a></li>
  <li><a class="letter" href="#">C</a></li>
  <li><a class="letter" href="#">D</a></li>
<ul id="names">
So when "A" is clicked, only "Australia" should be visible and when "B" is clicked then only "Bulgaria" should be visible. Got the idea?


Okay, to implement this feature below is the solution.
  • First hide the "names" list (List of countries).
  • After that write a click event on "a letter" tag, which gets called when any alphabet is clicked.
  • Inside the click event, first fetch the text of clicked alphabet.
  • After that loop through all the li element of "names" list.
  • Inside the loop, check if the first letter of li element text starts with the clicked alphabet. This can be done using indexOf method. If the index is 0 then that is the element which we want to show, otherwise hide.
So putting it all together, below is the complete jQuery code.
//Code Starts
   $("#names li").hide();
     var letter = $(this).html();
     $("#names li").each(function(){
     var liText = $(this).text();
     if(liText.indexOf(letter) == 0)   
//Code Ends
See result below.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..