Tim Cooke

Search and filter a HTML table with JavaScript

15th August 2020

Because the list of articles and book reviews on this website is getting longer I wanted a way to find the one I'm looking for quickly, so I decided that a search function would be a nice addition as well as a fun project.

Honestly though I'm really lazy so consulted the internet for how to do it. The solution I implemented is pretty much as presented in s3schools.com : How TO - Filter/Search Table.

HTML

<input type="text" class="searchInput" id="searchArticles" onkeyup="searchArticles()" placeholder="Search articles..">
<table id="articles">
    <tr><td><a href="/tablesearch">Search and filter a HTML table with JavaScript</a></td></tr>
    <tr><td><a href="/4of57python">Exercises for Programmers (Python): 4 of 57 - Mad Lib</a></td></tr>
    <tr><td><a href="/removelinuxservice">Remove a Linux service on Ubuntu</a></td></tr>
</table>

JavaScript

function searchArticles() {
    search('searchArticles', 'articles');
}
    
function search(searchInput, searchTable) {
    // Declare variables
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById(searchInput);
    filter = input.value.toUpperCase();
    table = document.getElementById(searchTable);
    tr = table.getElementsByTagName("tr");
    
    // Loop through all table rows, and hide those who don't match the search query
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
            txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

A little bit of CSS to make it look nice (also largely stolen from w3schools) and It's done.