0

I hope that you are well. I am attempting to write an HTML table filter in JavaScript, with the goal of including the table headers html tag "th" and first table subheader html tag "td" (the subheaders are emphasized with html tag "em") of the cell in the search result.

Is there a way to search for "th" and "em" tags in the html table? If I can search for those in my table data during the filter when the user types in the search bar, I reason that I can include them with the filtered results, and thus achieve the goal.

Advice is appreciated, I am very new to JavaScript.

My relevant javascript code is as follows, currently it only displays the filtered results, and not headings or subheadings:

function filterTable(event) {
var filter = event.target.value.toUpperCase();
var rows = document.querySelector("#multicategoryTable").rows;

for (var i = 0; i < rows.length; i++) {
    var Col0 = rows[i].cells[0].textContent.toUpperCase();
    var Col1 = rows[i].cells[1].textContent.toUpperCase();
    var Col2 = rows[i].cells[2].textContent.toUpperCase();
    var Col3 = rows[i].cells[3].textContent.toUpperCase();
    var Col4 = rows[i].cells[4].textContent.toUpperCase();
    var Col5 = rows[i].cells[5].textContent.toUpperCase();
    var Col6 = rows[i].cells[6].textContent.toUpperCase();
    if (Col0.indexOf(filter) > -1 || Col1.indexOf(filter) > -1 || Col2.indexOf(filter) > -1 || Col3.indexOf(filter) > -1 || Col4.indexOf(filter) > -1 || Col5.indexOf(filter) > -1 || Col6.indexOf(filter) > -1) 
    {
        rows[i].style.display = "";
    } 
    //else if (

    else 
    {
        rows[i].style.display = "none";
    }      
}

}

document.querySelector('#myInput').addEventListener('keyup', filterTable, false);

John
  • 1
  • 1
  • why dont just loop through again for your th element in #multicategoryTable – Kasnady Feb 15 '18 at 02:30
  • How would you detect an html element though? – John Feb 15 '18 at 14:16
  • I wrote a [very basic simple filter as a learning exercise](https://codepen.io/codemuggle/pen/XWVEBxW?editors=1010) once. But you are likely better off with something like [datatables](https://www.datatables.net/) or look at [answers here](https://stackoverflow.com/questions/9127498/) – surfmuggle Jan 18 '23 at 11:23

0 Answers0