tags:

views:

61

answers:

3
 <table width="600px" id='testTable'>
        <tr class="red"><td>this</td></tr>
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr class="red"><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr class="red"><td>this</td></tr>
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr class="red"><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
    </table>


.gray
{
    background-color:#dddddd;
}
.red
{
    color:Red;
}

    $(function () {
        $('#testTable tr.red:nth-child(odd)').addClass('gray');
       //this should select tr's with text=this, but its not happening
    });

i want to select all odds inside table which have class=red , but its not happening. please help

+3  A: 

nth-child(odd) selects the odd members of the element's parent not the odd members of the set returned by the selector.

You're looking for this:

$('#testTable tr.red').filter(':even').addClass('gray');

Edit: actually you want the even ones, i think. It's a 0-based index. Demo

ghoppe
yaa, it worked- thanx i was looking for this something like this.
Praveen Prasad
A: 

The combination of .red and :nth-child(odd) does not do what you think it does. Each of those two parts only applies to the tr element, not to each other. So it won't first find all red elements, then highlight alternate ones of those, it only selects rows where both "conditions" are true.

There is a solution in jQuery though - first select just the red elements, and use each:

$(function () {
    $('#testTable tr.red').each( function(i) {
        if ( i%2 == 1 )
            $(this).addClass('gray');
    });
});
DisgruntledGoat
This will work if you change `if ( i%2 == 1 )` to `if ( i%2 == 0 )` -- he's looking to change the rows with text: "this".
ghoppe
i was planning to do something like this but ghoppe's answer solved my problem
Praveen Prasad
A: 

Hi,

Why dont you try something a little more long winded such as

$(function() {
    $('#testTable tr:nth-child(odd)').each(function() {
        if($(this).hasClass('red')) { $(this).addClass('grey'); }
    });
});

This should do what your asking for

Anthony
This doesn't do what he wants. see his comment: "this should select tr's with text=this, but its not happening"
ghoppe
the last line states he wants all odds in the table that have a class of red, that's what this does ...Though I should have looked closer at the table mark up.
Anthony