Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a javascript search function that I am trying to work with DIV's in html, it works with tables and underlined lists. However, I cannot get it to go though the same list of DIV's and searching through the hyperlink text.

HTML Search:

HTML
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for text..">



HTML:

HTML
<div id ="main_divs">
<div><a href ="link.html">Text1</a></div>
<div><a href ="link.html">Text2</a></div>
<div><a href ="link.html">Text3</a></div>
<div><a href ="link.html">Text4</a></div>
<div><a href ="link.html">Text5</a></div>
<div><a href ="link.html">Text6</a></div>
</div>


Javascript function:

JavaScript
function myFunction() {
      // Declare variables
      var input, filter, div, div_item, ahref, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      div = document.getElementById("main_divs");
7     div_item = div.getElementsByTagName("div");

      for (i = 0; i < div_item.length; i++) {
        ahref = div_item[i].getElementsByTagName("a")[0];
        if (ahref) {
          txtValue = ahref.textContent || ahref.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            div_item[i].style.display = "";
          } else {
            div_item[i].style.display = "none";
          }
        }
      }
    }


What I have tried:

I keep getting an error on "div_item = div.getElementsByTagName("div");" It is line 7.

Error: Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

It worked great with an underlined list and a table, it is not working with DIV's, for some reason. So do I need to create a completely different type of search function if I am only using DIV's vs. a table or a list, or I am missing something simple?
Posted
Updated 7-Sep-21 21:51pm

1 solution

Your code works fine for me:
Edit fiddle - JSFiddle - Code Playground[^]

The error suggests that there is no element in the document with id="main_divs". Double-check that you have the same ID in your HTML and Javascript.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900