Categories
Mastering Development

Javascript search with includes for each DIV

I am trying to develop a filter function with includes. As for now, I have 3 main DIV, and each main DIV has its own DIV. The current script I have now only worked on main DIV.

Instead of highlighting main DIV, I only want to highlight matched char DIV.

For example, when key in ‘inner’, Inner First and Inner Sec will be highlighted. When key in ‘Inner First’, only DIV for Inner First will be highlighted.

Would appreciate if anyone of you can help me. Thanks in advance.

function myFunction() {
  var input = document.getElementById("Search");
  var filter = input.value.toLowerCase();
  var nodes = document.getElementsByClassName('target');
  for (i = 0; i < nodes.length; i++) {
    nodes[i].style.backgroundColor = "";
    if (input.value !== '') {
      if (nodes[i].innerText.toLowerCase().includes(filter)) {
        nodes[i].style.backgroundColor = "blue";
        for (j = 0; j < nodes[i].length; j++) {
          nodes[j].style.backgroundColor = "";
          if (input.value !== '') {
            if (nodes[j].innerText.toLowerCase().includes(filter)) {
              nodes[j].style.backgroundColor = "grey";
              for (k = 0; k < nodes[j].length; k++) {
                nodes[k].style.backgroundColor = "";
                if (input.value !== '') {
                  if (nodes[k].innerText.toLowerCase().includes(filter)) {
                    nodes[k].style.backgroundColor = "yellow";
                  } else {
                    nodes[k].style.backgroundColor = "red";
                  }
                }
              }
            } else {
              nodes[j].style.backgroundColor = "red";
            }
          }
        }
      } else {
        nodes[i].style.backgroundColor = "red";
      }
    }
  }

}
<table align="center" width="20%">
  <tr>
    <td style="padding-right: 10px">
      <input type="text" id="Search" title="Type in a name">
      <button onclick="myFunction()">
        Click to search
      </button>
    </td>
  </tr>
</table>
<br>
<div class="target">
  This is my DIV element.
  <div class="target">
    Inner First
    <div class="target">
      Inner Sec
    </div>
  </div>
</div>
<div class="target">
  This is another Div element.
</div>
<div class="target">
  Can you find me?
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *