I got a customize li filter for a website but I need to hide the all li in the initial stage. I need to hide all li in the page and show only the searching li. But the problem is when I try to hide the li, it also block all the li during result.
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search...">
<ul id="myUL">
<li><a href="#">tree</a></li>
<li><a href="#">bike</a></li>
<li><a href="#">sea</a></li>
<li><a href="#">mobile</a></li>
</ul>
You can hide all the li
elements if the input is an empty string i.e. ""
and run the function when the user types in input and the first time when the JS loads.
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
if (input.value === "") {
[...li].forEach((liElement) => {
liElement.style.display = "none";
});
} else {
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
}
myFunction();
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search...">
<ul id="myUL">
<li><a href="#">tree</a></li>
<li><a href="#">bike</a></li>
<li><a href="#">sea</a></li>
<li><a href="#">mobile</a></li>
</ul>