How to count visible 'li' on a search list

Viewed 2565

The code below is for a simple search. Im trying to count the visible 'li' on the list and display the total in a div "totalClasses". and then when the user search for a class update the total with only the visible classes(li).

I have tried doing this ('li:visble') but is not working.

ul = document.getElementById('myUl');
li = ul.getElementsByTagName('li');
aa = ul.getElementsByTagName('li:visible');
document.getElementById('totalClasess').innerHTML = (aa.length) + " Results";

function search() {
  var input, filter, ul, li, a, aa;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById('myUl');
  li = ul.getElementsByTagName('li');

  for (var i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName('a')[0];
    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = '';
    } else {
      li[i].style.display = 'none';
    }
  }
}
<input type="text" id="myInput" onkeyup="search()" placeholder="Search for a class..." title="Type something">
<p class="results">Results</p>
<p id="totalClasess"></p>
<ul id="myUl">
  <li><a href="#" class="header">Section 1</a></li>
  <li><a href="#">Class 1 </a></li>
  <li><a href="#">Class 2</a></li>
  <li><a href="#">Class 3</a></li>
</ul>

DEMO: https://jsfiddle.net/52bbqor9/

8 Answers
Related