Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I use jquery addClass when selecting a tr to override a nth-child class on a parent div?

Tags:

jquery

css

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?

like image 951
vinylDeveloper Avatar asked Dec 07 '25 00:12

vinylDeveloper


1 Answers

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!

like image 175
adeneo Avatar answered Dec 08 '25 15:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!