Q:

Iterating and conditionally hiding multiple elements with jQuery

if ( $("table tbody tr:visible").length === 0 ) { 
    $("table thead").hide();
} else {
    $("table thead").show();
}

I'd like to hide the thead element of all table elements that have a tbody with only hidden tr elements.
The code above works for one table, but not for multiple tables. I have lots of tables and this code searches for all tbody tr of all tables at once, instead of each table on its own.
Do I need to get $("table").length and check each for visible trs? Is there a simpler solution?

A:

You can also accomplish this without an explicit loop in your code. jQuery's :has() selector can take care of this for you in one line.
$("table:not(:has(tbody tr:visible)) thead").hide();

Using this, you can directly query all thead elements whose parent tables don't contain any visible tr elements within their tbody.
You can see this in action here.

