0
<table>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
    <tr>
        <th>A</th>
        <th>B</th>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
</table>

I want to apply border-bottom to this kind of <table> but I don't know how to select the last not empty <tr>, is there any other way to do it ?

PS: I don't know how many <td> or empty <tr> in the <table>


In other words, I want the red border on the bottom of this table https://jsfiddle.net/37L334hj/68/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
BabyCabbage
  • 187
  • 1
  • 9

1 Answers1

1

There's not really a great way to do complex CSS selectors that look backwards. If your table is even slightly more complex, using Next Sibling and General Sibling CSS selectors will get pretty ugly pretty quick. Can you use some JavaScript? It would be trivial, only 2 or 3 lines. Also note that you can't actually add border parameters to a tr, but you can to the td. For this example I just did a 1px box shadow.

let rows = document.querySelectorAll('tr:not(.empty-row)');
let lastRow = rows[rows.length - 1];

lastRow.setAttribute( 'style', 'box-shadow: 0 1px 0 red' );
<table>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
    <tr>
        <th>A</th>
        <th>B</th>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
    <tr>
        <td>c</td>
        <td>d</td>
    </tr>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
</table>

All that said, if you just need a border on the bottom of the table, can you just put a border on the bottom of the table and set the .empty-row class to display: none;?

table { border-bottom: 1px solid green; }
tr.empty-row { display: none; }
<table>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
    <tr>
        <th>A</th>
        <th>B</th>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
    <tr>
        <td>c</td>
        <td>d</td>
    </tr>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
</table>
Xhynk
  • 13,513
  • 8
  • 32
  • 69