Q:

I'm trying to understand indexOf

So I found this code on w3 schools when I was looking to figure out how to put a search bar in my dropdown box in my website. I cannot however understand how the code works at all. Everytime I think I get close to understanding it I get confused
function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
   }
}

So I understand that "a" is a list of all my elements and that it the first one has a value of 0 then 1, 2, 3, etc. I don't understand how I retrieve the text that I'm putting in the box and how it gets filtered. So in the txtValue string its changing the text to uppercase but how is it getting the text, and then how does it know what to filter. Also I'm very confused about the -1.
If anyone could help me understand I'd greatly appreciate it.

A:

Functionality of your code
The code you've posted loops over the elements in a and checks whether each element's text content (either textContent or innerText) contains the given filter value as a substring. The value of filter comes from the input element filter. If the element's text does contain filter as a substring, the CSS display value of the element is set to "" (default), otherwise the element is hidden by setting its CSS display value to "none".
For example if you have the a elements:
<a href="http://a.com">Great Site</a>
<a href="http://b.com">Okay Site</a>
<a href="http://c.com">Great Website</a>

And entered "great" in to the filter input. The first and last elements would have their CSS display properties set to "" and would therefore remain visible. While the middle element would have its display set to "none" and would become hidden.
indexOf
The indexOf method in JavaScript returns the index of the first occurrence of the given element in an array or string. For example 'abcb'.indexOf('b') returns 1. If the element is not found in the array, indexOf returns -1.
So the line:
if (txtValue.toUpperCase().indexOf(filter) > -1) {

really just checks if filter is a substring of txtValue.
A more straightforward way of getting the same functionality would be to use the includes method. For example:
if (txtValue.toUpperCase().includes(filter)) {

Note also that the call of toUpperCase is only done to perform the substring search in a case-insensitive way, so that "Hello" would match "hEllo".

