Why does this javascript code that is supposed to only show results that match typed input filter only the first 10 options?

I have a piece of code (only a snippet, everything else is css) that as I type shows only the options that match my typed input. But for some reason, it only filters the first 10 options. The rest of the options just show no matter what. Any ideas why?

function myFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("mySearch");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myMenu");
  li = ul.getElementsByTagName("li");
  for (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";
    }
  }
}
a { color: white }
<div class="row">
  <div class="left" style="background-color:#2D2D2D; color: white;">
    <h2>***PAVADINIMAS***</h2>
    <input type="text" id="mySearch" onkeyup="myFunction()" placeholder="PaieŇ°ka" title="Type in a category">
    <ul id="myMenu">
      <li><a href="#">Option1</a></li>
      <li><a href="#">Test</a></li>
      <li><a href="#">Lorem ipsum</a></li>
      <li><a href="#">abcde</a></li>
      <li><a href="#">monday</a></li>
      <li><a href="#">tuesday</a></li>
      <li><a href="#">wednesday</a></li>
      <li><a href="#">thrusday</a></li>
      <li><a href="#">friday</a></li>
      <li><a href="#">saturday</a>
      <li>
      <li><a href="#">sunday</a></li>
      <li><a href="#">test2</a></li>
      <li><a href="#">iii</a></li>
      <li><a href="#">12345</a></li>
      <li><a href="#">qwerty</a></li>
    </ul>
  </div>

I searched the web but haven’t found anything similar to this.

>Solution :

Your extra <li> tag is rendered by the browser as an empty <li> element (i.e. <li></li>). Thus, when it is looped over by your for loop, the following lines fail:

a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {

because the empty li element doesn’t contain an a element, and thus the a variable is undefined, causing a.innerHTML to throw an error (since you can’t access a property on an undefined value).

Leave a Reply