Super Man
Super Man

Reputation: 129

Applying CSS class to all rows but not the table heading

I am trying to apply a css style to change color of clicked rows of an HTML table. On the click event, I am adding the class (selected-row). Now, my table has a sorting functionality when clicking on the heading of each column. The heading gets colored which is not what I want. I want only rows but not the heading. So, I changed my style to (not first child). Now, the heading AND first row don't get color changed. I need only the heading to NOT change color and all other rows to change color when I add selected-row class.

.selected-row:not(:first-child) {
    background-color: brown;
    color: #FFF;
}

            $("#example tr").click(function () {
                $(this).addClass('selected-row').siblings().removeClass('selected-row');


            });

Upvotes: 0

Views: 1923

Answers (5)

Nachshon Schwartz
Nachshon Schwartz

Reputation: 15765

Use th for the header row element.

Upvotes: 0

Garrett
Garrett

Reputation: 106

If you don't want to modify your header using the th or tbody tags, you could do something like this.

$("table tr:gt(0)").click(function(){
    $(this).siblings().removeClass('selected-row');
    $(this).addClass('selected-row');
})

You can see this working in this jsfiddle

Upvotes: 0

tomsmithweb
tomsmithweb

Reputation: 371

You can target "td" tags:

$("#example tr td").click(function () {
                $(this).parent().addClass('selectedrow').siblings().removeClass('selected-row');

If you are using "th" tags in your table:

<table style="width:100%">
      <tr>
        <th>Firstname</th>
        <th>Lastname</th> 
        <th>Age</th>
      </tr>
      <tr>
        <td>Jill</td>
        <td>Smith</td> 
        <td>50</td>
      </tr>
   </table>

Upvotes: 0

Nick
Nick

Reputation: 16576

One way to potentially do it would be to wrap your table header in <thead></thead> and body in <tbody></tbody> and then apply whatever selector as

$("#example tbody tr").click(function () {...});

Upvotes: 0

Fenton
Fenton

Reputation: 250822

If you mark up your table with a <thead> to contain the header row, and <tbody> to contain the data rows, you can specifically target only rows in the table body - like this in CSS:

tbody > tr { }

And like this in jQuery:

$('#example tbody > tr')...

Table mark-up:

<table>
    <caption>This table contains...</caption>
    <thead>
        <tr>
            <th>Heading</th>
            <th>Heading</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td>Total</td>
            <td>$50</td>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Item 1</td>
            <td>$20</td>
        </tr>
        <tr>
            <td>Item 2</td>
            <td>$30</td>
        </tr>
    </tbody>
</table>

Upvotes: 2

Related Questions