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.

Problem:

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>
</ol>
<br/>
<ul id="names">
  <li>Australia</li>
  <li>Bulgaria</li>
  <li>Denmark</li>
</ul>?

So when "A" is clicked, only "Australia" should be visible and when "B" is clicked then only "Bulgaria" should be visible. Got the idea?

Solution:

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
$(document).ready(function(){
   $("#names li").hide();
   $("a.letter").click(function(){
     var letter = $(this).html();
     $("#names li").each(function(){
     var liText = $(this).text();
     if(liText.indexOf(letter) == 0)   
         $(this).show();
     else
        $(this).hide();           
    });      
 });
});?
//Code Ends

See result below.

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



Responsive Menu
Add more content here...