Sunandha
Sunandha

Reputation: 3

How to hide all child elements except first child element using CSS

I have a table which is looping dynamically. Now I need to hide all <tr> with the class .dynamic-tr except 1st table's <tr class="dynamic-tr"> by using CSS.

<table class="dynamic-table">
  <tr class="dynamic-tr">
    <th>Resource Name</th>
    <th>Allocation</th>
  </tr>
  <tr>
    <td>John</td>
    <td>100%</td>
  </tr>
</table>
<table class="dynamic-table">
  <tr class="dynamic-tr">
    <th>Resource Name</th>
    <th>Allocation</th>
  </tr>
  <tr>
    <td>Alex</td>
    <td>50%</td>
  </tr>
</table>
<table class="dynamic-table">
  <tr class="dynamic-tr">
    <th>Resource Name</th>
    <th>Allocation</th>
  </tr>
  <tr>
    <td>Bryce</td>
    <td>100%</td>
  </tr>
</table>

I have tried with this CSS but its not working. Can somebody please suggest.

.dynamic-table .dynamic-tr {
  display: none;
}
.dynamic-table:first-of-type .dynamic-tr {
  display: block;
}

Upvotes: 0

Views: 1185

Answers (2)

Henry Le Berre
Henry Le Berre

Reputation: 910

Does this satisfy your requirements ?

body > table > tbody > tr.dynamic-tr { display: none; }
body > table:first-of-type > tbody > tr.dynamic-tr {display: inline;}

Upvotes: -1

Mihai T
Mihai T

Reputation: 17687

Use :not to achieve what you need.

table.dynamic-table:not(:first-child) .dynamic-tr {
    display:none;
}
<table class="dynamic-table">
  <tr class="dynamic-tr">
    <th>Resource Name</th>
    <th>Allocation</th>
  </tr>
  <tr>
    <td>John</td>
    <td>100%</td>
  </tr>
</table>
<table class="dynamic-table">
  <tr class="dynamic-tr">
    <th>Resource Name</th>
    <th>Allocation</th>
  </tr>
  <tr>
    <td>Alex</td>
    <td>50%</td>
  </tr>
</table>
<table class="dynamic-table">
  <tr class="dynamic-tr">
    <th>Resource Name</th>
    <th>Allocation</th>
  </tr>
  <tr>
    <td>Bryce</td>
    <td>100%</td>
  </tr>
</table>

Upvotes: 3

Related Questions