Babulaas
Babulaas

Reputation: 869

CSS Select all HTML elements except first row of every table

When you have a random HTML Page. I really doesn't matter what the content is or the structure

What I want is to select all elements except the first row (TR) of every table that is exist on the page.

the following selector doesn't work:

* :not(tr:first-child){ /* DO SOMETHING */}

The table that is rendered is just a plain table whithout any table headers like:

<p>123</p>
<table>
  <tr>
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr>
    <td>a</td><td>b</td><td>c</td>
  </tr>
</table>
<div>bla bla</div>

Upvotes: 1

Views: 3052

Answers (2)

Takit Isy
Takit Isy

Reputation: 10081

You may want to stylize the table content, but not the "header".

An easy way to do that is to use tds for the content, and ths for the header, as th is used to define a header cell in an HTML table. (You can even remember it saying th = table header.)

Then, you'll only have to target the tds:

table {
  border-collapse: collapse;
}

/* Add your style here */
td {
  border: 1px solid gray;
  padding: 8px 20px;
  background: #ddd;
}
<p>123</p>
<table>
  <tr>
    <th>1</th><th>2</th><th>3</th><!-- Note the ths here! -->
  </tr>
  <tr>
    <td>a</td><td>b</td><td>c</td>
  </tr>
  <tr>
    <td>d</td><td>f</td><td>g</td>
  </tr>
</table>
<div>bla bla</div>


⋅ ⋅ ⋅

If you can't use ths…
As you may already have some styling applied on your tds, it's better to use this kind of selector to match the tds that are in the trs except the first one:

table {
  border-collapse: collapse;
}

td {
  border: 1px solid gray;
  padding: 8px 20px;
}

/* Stylize all tds in trs except in the first one! */
table tr:not(:first-child) td {
  background: #ddd;
}
<p>123</p>
<table><!-- All the elements are tds in the trs! -->
  <tr>
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr>
    <td>a</td><td>b</td><td>c</td>
  </tr>
  <tr>
    <td>d</td><td>f</td><td>g</td>
  </tr>
</table>
<div>bla bla</div>

Hope it helps.

Upvotes: 2

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18113

How about this workaround:

* {
  color: green;
}
table tr:first-of-type td {
  color: red;
}
<p>test</p>
<ul>
  <li>item</li>
  <li>item</li>
</ul>
<table>
  <tr>
    <td>cell</td>
    <td>cell</td>
  </tr>
  <tr>
    <td>cell</td>
    <td>cell</td>
  </tr>
  <tr>
    <td>cell</td>
    <td>cell</td>
  </tr>
</table>
<p>test</p>
<ul>
  <li>item</li>
  <li>item</li>
</ul>
<table>
  <tr>
    <td>cell</td>
    <td>cell</td>
  </tr>
  <tr>
    <td>cell</td>
    <td>cell</td>
  </tr>
  <tr>
    <td>cell</td>
    <td>cell</td>
  </tr>
</table>

Upvotes: 0

Related Questions