HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Learn how to create a search menu to filter links with JavaScript
How to search for links in a navigation menu:
Start to type for a specific category/link inside the search bar to "filter" the search options.
Some text..Some text..Some text..Some text..Some text..Some text..Some text..Some text..
Some other text..Some text..Some text..Some text..Some text..Some text..Some text..Some text..
Some text..
function myFunction() { var input, filter, ul, li, a, i; input = document.getElementById("mySearch"); filter = input.value.toUpperCase(); ul = document.getElementById("myMenu"); li = ul.getElementsByTagName("li"); for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } }
Step 1) Add HTML:
<input type="text" id="mySearch" onkeyup="myFunction()" placeholder="Search.."
title="Type in a category">
<ul id="myMenu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
<li><a href="#">PHP</a></li>
<li><a href="#">Python</a></li>
<li><a href="#">jQuery</a></li>
<li><a href="#">SQL</a></li>
<li><a href="#">Bootstrap</a></li>
<li><a href="#">Node.js</a></li>
</ul>
Step 2) Add CSS:
Style the search box and the navigation menu:
/* Style the search box */
#mySearch {
width: 100%;
font-size: 18px;
padding: 11px;
border: 1px solid #ddd;
}
/* Style the navigation
menu */
#myMenu {
list-style-type: none;
padding: 0;
margin: 0;
}
/* Style the navigation links */
#myMenu li a {
padding: 12px;
text-decoration: none;
color: black;
display: block
}
#myMenu li a:hover {
background-color: #eee;
}
Step 3) Add JavaScript:
<script>
function myFunction() {
// Declare variables
var input, filter,
ul, li, a, i;
input = document.getElementById("mySearch");
filter = input.value.toUpperCase();
ul =
document.getElementById("myMenu");
li =
ul.getElementsByTagName("li");
// Loop through all
list items, and hide those who don't match the search query
for (i = 0; i <
li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
}
else {
li[i].style.display = "none";
}
}
}
</script>
Try it Yourself »
Tip: Remove toUpperCase() if you want to perform a case-sensitive search.