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);
<script src=""></script>
<form action="#" novalidate="novalidate">
  <input id="searchInputField" type="search" placeholder="Find" autocomplete="off">
<ul class="nav_links">
    <span class="link_name navItem">Home</span>
      <span class="link_name navItem">Costing Logistics</span>
    <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>

The JSFiddle


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.)