jQuery - how to select a tr that contains th's?
-
22-08-2019 - |
Question
Title pretty much says it all.
Given a table like
<table>
<tr>
<th>Header 1</td>
<th>Header 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
</table>
How to select the row which contains the th headers and no other?
Solution
Expression:
$(function() {
$("tr:has(th):not(:has(td))").hide();
});
or even just:
$(function() {
$("tr:not(:has(td))").hide();
});
Full example:
<html>
<head>
<title>Layout</title>
</head>
<body>
<table>
<tr>
<th>Header 1</td>
<th>Header 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<th>Header 3</th>
<th>Datum 2</td>
</tr>
</table>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function() {
$(function() {
$("tr:has(th):not(:has(td))").hide();
});
});
</script>
</body>
</html>
OTHER TIPS
If possible, it would be ideal to enclose your table header inside a <thead> element
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
That way, selecting your table header would be as simple as:
$('thead');
Or selecting only the <tr>
$('thead tr');
Your markup would then be more readable, and styling your table becomes easier, as you can more easily target elements in the header or body of your table.
jQuery("tr:has(th)")
will select every tr
that contains at least one th
kthxbye :)
Use the :has
selector:
$('tr:has(th)').addClass('sample')
Probably won't work if you have a table with mixed th
and td
children though.
Dunno if it's like Dojo CSS3 queries, but you could use the first-child pseudo class, if jQuery supports it:
tr th:first-child
or
tr th:nth-child(1)
See: http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/