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:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for text..">
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:
function myFunction() {
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?