Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 323
noowie Avatar asked Mar 08 '26 20:03

noowie


1 Answers

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>
like image 145
Oen44 Avatar answered Mar 11 '26 09:03

Oen44



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!