3
votes

I am using this to select a tr when clicked on to change the color of a tr.

$("tr").click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
});

See fiddle http://jsfiddle.net/4sn38/3/

but when I use a nth-child class on the parent div to set the tr background, my addClass isn't getting added. How can I use the nth-child class in tandem with my jquery addClass function?

this is what I'm trying to do

See fiddle http://jsfiddle.net/4sn38/

this didn't work

$(".list tr:nth-child(1)").addClass("selected").siblings().removeClass("selected");

this changes the color, but then I can't remove it when another is clicked

$(this).css('background','blue');

Any ideas what I'm doing wrong?

1
there is a problem with css specificity jsfiddle.net/arunpjohny/sUjQW/1 - Arun P Johny
I didn't get what you are trying to do - Arun P Johny
haha, well you fixed it!! Thanks, make and an answer and I'll accept, although the answer by @adeneo also was the cause of the issue. Thanks - vinylDeveloper
since you have the answer already from @adeneo accept it - Arun P Johny
awesome… thanks for the help - vinylDeveloper

1 Answers

6
votes

The javascript seems to be working just fine, the issue is not being more specific with your CSS, as this

.list tr:nth-child(odd) {
    background: #CCC; 
}

is more specific than this:

tr.selected {
    background-color: #FFCF8B;
}

so you have to change it to

.list tr.selected {
    background-color: #FFCF8B;
}

FIDDLE

Read more on CSS specificity!