Search <div> for text

noowie picture noowie · May 6, 2017 · Viewed 12.8k times · Source

I am trying to search EACH on a single HTML5 page, and then HIDE the if there is no match. I am 'almost' but not quite there. So far, my will disappear if there is a match of a single char, but then reappear if i type anything else. Also, i would like the page to reset if i clear the search box. Would really appreciate if you Java guys could take a look.

Answer

Oen44 picture Oen44 · May 6, 2017

There you go. Used includes method that fit your needs.

function myFunction() {
  var input = document.getElementById("Search");
  var filter = input.value.toLowerCase();
  var nodes = document.getElementsByClassName('target');

  for (i = 0; i < nodes.length; i++) {
    if (nodes[i].innerText.toLowerCase().includes(filter)) {
      nodes[i].style.display = "block";
    } else {
      nodes[i].style.display = "none";
    }
  }
}
<table align="center" width="20%">
  <tr>
    <td style="padding-right: 10px">
      <input type="text" id="Search" onkeyup="myFunction()" placeholder="Please enter a search term.." title="Type in a name">
    </td>
  </tr>
</table>
<br>


<div class="target">
  This is my DIV element.
</div>
<div class="target">
  This is another Div element.
</div>
<div class="target">
  Can you find me?
</div>