Search code examples
javascriptjqueryhtmltext-search

Search <div> for text


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.

function myFunction() {
    input = document.getElementById("Search");
    filter = input.value.toUpperCase();
    for (i=0; i<document.getElementsByClassName('target').length; i++){
if(document.getElementsByClassName('target'[i].innerHTML.toUpperCase().indexOf(filter) > -1) {     
    document.getElementsByClassName("target")[i].style.display = "none";
            }
        else{
        	document.getElementsByClassName("target")[i].style.display = "";
        } 
    }
}
    </script>
    <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>


Solution

  • 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 (let 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>