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/
you need to update the count everytime you call the event handler. you can do like this:
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');
var liCount = 0;
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 = '';
liCount++;
} else {
li[i].style.display = 'none';
}
}
document.getElementById('totalClasess').innerHTML = liCount + " Results";
}
'li:visible' is not a tag, you are adding a pseudo-selector and hoping for the best, which won't work.
You could go
ul.querySelectorAll('li:visible')
If you don't care about Firefox. If you do, I'd recommend jQuery.
ul.find('li:visible');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With