1
<table>
    <thead>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
        <tr>
            <td>sf</td>
        </tr>
    </thead>
</table>


.red {
  background-color: red;
}
.green {
  background-color: green;
}

How can i make automatically add class red and green for TR with jQuery?

LIVE EXAMPLE: http://jsfiddle.net/2Htwx/

1
  • 1
    $('tr').addClass('red').addClass('green')? Commented Feb 24, 2012 at 13:55

6 Answers 6

4
$('tr:odd').addClass('red');
$('tr:even').addClass('green');​

Assuming you want every other row red or green, as per your JS-fiddle. Note that this is within each table, so you won't see red/green/red across ALL table rows.

If you want that, try this:

var oddFilter = function(index) {
     console.log(index);
  return (index % 2) == 1;
},
 evenFilter = function(index) {
     console.log(index);
  return (index % 2) == 0;
}

$('tr').filter(oddFilter).addClass('red').end()
       .filter(evenFilter).addClass('green');​

Note that <thead>, <tfoot> etc can still mess up the display, since that moves rows around the display.

Sign up to request clarification or add additional context in comments.

Comments

4

You don't need JavaScript to accomplish this 'table-striping' effect. Use of the CSS nth-child selector will do the trick

thead tr {
    background: green; /* Set all tr elements to green */
}

thead tr:nth-child(even) {
    background: red; /* Override the colour for just the even ones */
}

Note: This selector is not supported in older browsers. IE8 and down.

Further reading on CSS nth-child:

1 Comment

selectivzr adds support for this selector to old versions of IE: selectivizr.com
1

You mean like this?

$(document).ready(function() {
     var class = "";
     $("tr").each(function(idx, elem) {
        class = (idx % 2 == 0)?"red":"green";
        $(elem).addClass(class);
     });
});

Comments

1

Could you please explain "automatically"? You mean at page ready event?

Maybe somthing like this:

$(document).ready(function (){
    $("tr:odd").css("background-color", "#f00");
    $("tr:even").css("background-color", "#0f0");
});

Comments

0

Here's the simplest method:

$("tr").addClass("red");

Comments

0

try this

var trs = jQuery('tr');
trs.filter(':even').addClass('red');
trs.filter(':odd').addClass('green');

to not selecting two-times every tr

1 Comment

i did not downvote, but i assume the person who did did so because the fiddle shows alternating red and green, not every row red AND green.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.