Skip to content
Advertisement

Filter HTML Table using JavaScript – textContent Error

Desired Result: Input data from a .csv file into PHP. Take the data from the .csv file and store into an array. Store the array into an HTML table using PHP. Use a search engine to filter through the rows using JavaScript.

I am getting the following error in the JavaScript: Uncaught TypeError: Cannot read property ‘textContent’ of null

JavaScript

Using the console.log, I have been able to determine it is reading and looping through each row in the table correctly, but it is unable to loop through the ‘td’ to determine if it matches text in the search engine.

The Array is a NodeList when consoling out the rows if that information is useful.

Happy to upload more information if needed. Thank you for your help in advance!

EDIT Adding in minimal HTML. The table contains 15 rows, but for the purposes of this, only adding in a few. This table is creating from an array using PHP.

EDIT 2 Headers added into thead

JavaScript

Advertisement

Answer

  • Your HTML table markup is not correct. The row with the <th>s should go in <thead> not in <tbody>
  • You’re using invalid ternary operator syntax ; ? x : y.
  • Use rather the "input" event to account for mouse copy/paste stuff etc.

JavaScript

But keep in mind that row.querySelector("td") will only get the first TD in a row (not all of them):

Match for multiple cells using Array.prototype.some()

Here’s an example that will allow you to search throughout any cell, and uses a better solution for the toggling by using Element.classList.toggle() (and .includes() instead of .startsWith())

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement