Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to select a tr that contains th's?

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?

like image 387
George Mauer Avatar asked Feb 09 '09 23:02

George Mauer


People also ask

How do I select a specific row in a table using jQuery?

In order to use jQuery in the HTML file, we will add the below syntax inside the <head> tag. Syntax for selecting odd rows: $("table tr:odd").

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

Can you use css selectors in jQuery for selecting elements?

jQuery uses CSS-style selectors to select parts, or elements, of an HTML page. It then lets you do something with the elements using jQuery methods, or functions. To use one of these selectors, type a dollar sign and parentheses after it: $() . This is shorthand for the jQuery() function.


1 Answers

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>
like image 129
cletus Avatar answered Sep 19 '22 01:09

cletus