Filter table rows with jquery

mko picture mko · Oct 31, 2011 · Viewed 24.7k times · Source

I would like to know how to filter table rows based on a column value. Plugins excluded, I would like to figure it out how to make this thing to work.

Answer

James Allardice picture James Allardice · Oct 31, 2011

Your question is quite vague, but the general idea would be something like this:

$("td").filter(function() {
    return $(this).text().indexOf("whatever") !== -1;
}).parent().remove();

Here's a working example. It first selects all table cells, then filters them based on some text, and removes the parent (which should be the tr) of any remaining rows.

If you don't care about individual columns, you can select the tr elements and get rid of the call to parent. That will still work because text will return the text of all the children of the selected tr.

Update based on comments

The above will remove the matching table rows from the DOM completely. If you want to just hide them, you can replace remove with hide. If you then wanted to make the rows visible again you could simply do something like:

$("tr").show();

Which selects all the tr elements and shows them (ones that are already visible will not be affected, so just the ones previously hidden will become visible again).