how can i count the filtered rows of a table. The table has many rows. it is just normal containing many rows. With the help of following Javascript code. I filter data, by way of typing into input text, pasting the required value and also with a click to import the value from OptionList; and all these three ways are functioning perfectly. If it is possible to amend this code so as to get the count of filtered rows out of total rows, i.e. "Found….. rows out of……rows. at the top of table. I am totally a new user of javascript without any previous knowledge so sorry for that. The code is :
const trs = document.getElementById("myTable").getElementsByTagName("tr");
document.getElementById("search").addEventListener("input", filterRows);
document.getElementById("search").addEventListener("change", filterRows);
document.getElementById("search").addEventListener("click", filterRows);
function filterRows(e) {
const query = e.target.value.toLowerCase();
for (const tr of trs) {
tr.style.display = tr.innerText.toLowerCase().includes(query) ? "" : "none";
}
}
2
Answers
When you query the DOM with something like
getElementsByTagName()
, it returns a collection of elements. This collection has thelength
property, so if you wanted to know how many rows you had in total, you could just usetrs.length
. Though you still need to get the count that’s visible after filtering.I would do something different in your code. I would add a class for
filtered
to your CSS:Then, in your loop:
That will add/remove the
filtered
class as appropriate.Then, if you want the count…
One final note… I’d recommend avoiding the usage of IDs. They clutter up the global namespace and can cause conflicts when you add code later on.
This code filters a value from input to your table and shows rows and count.