How to search for items inside a nested list

So i am trying to get only the searched items with a hierarchy using the input box at the top of the page.

My current code only shows the main list items in the parent list.

Current Results:

enter image description here

Desired Results:

enter image description here

$("#searchInputField").on("input", function() {
  var searchTerms = $(this).val().toLowerCase();
  $(".nav_links li").each(function() {
    var hasMatch = searchTerms.length == 0 || $(this).text().toLowerCase().indexOf(searchTerms) > 0;
    var listItem = $(this);
    listItem.toggle(hasMatch);
  });
});
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<form action="#" novalidate="novalidate">
  <input id="searchInputField" type="search" placeholder="Find" autocomplete="off">
</form>
<ul class="nav_links">
  <li>
    <span class="link_name navItem">Home</span>
  </li>
  <li>
    <div>
      <span class="link_name navItem">Costing Logistics</span>
    </div>
    <ul class="sub-menu">
      <li><span class="navItem">HTML & CSS</span></li>
      <li><span class="navItem">JavaScript</span></li>
      <li><span class="navItem">PHP & MySQL</span></li>
    </ul>
  </li>
</ul>

The JSFiddle https://jsfiddle.net/abdotamer3/j7tdo18y/5/

Answer

You have a typo in your javascript. indexOf() returns the position of the search term in your text, so when you write indexOf(searchTerms) > 0, you’re asking for all list items where the search term is present at the second character or later. This is easily confirmed – search for “TML” or “vascript” and you’ll get results.

Change it to

var hasMatch = searchTerms.length == 0 || $(this).text().toLowerCase().indexOf(searchTerms) >= 0;

and your code should work again.

(Basically, change > 0 to >= 0. Or you can change it to != -1 and get the same result.)