KNU
KNU

Reputation: 2515

can't set color using jQuery

I've started learning jQuery and I was trying to set the color of a tr but unable to do so. However, I'm able to successfully update other css attribute e.g. font-style. From what I've learnt so far to set the CSS property and value we use:

$(selector).css(property,value)

So, please point out the error.

HTML:

<table class="csr">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>

<table class="aTable">
<tr><td>Row 11</td></tr>
<tr><td>Row 22</td></tr>
<tr><td>Row 33</td></tr>
</table>

CSS:

td {
    color: blue;
    font-weight: bold;
  }

table.aTable td{
    color: red;
    font-weight: bold;
  }

jQuery:

$( "tr:first" ).css( "font-style", "italic" );
$( "tr:first" ).css( "color", "red" );
$( "tr:first" ).css( "background-color","yellow" );

$( ".aTable tr:first" ).css( "font-style", "italic" );
$( ".aTable tr:first" ).css( "background-color","yellow" );

Upvotes: 0

Views: 670

Answers (3)

Amit
Amit

Reputation: 15387

You need to set as below:

$( "tr:first>td" ).css( "color", "red" );

DEMO

Upvotes: 0

MiltoxBeyond
MiltoxBeyond

Reputation: 2731

You are applying the css attributes to the TR which is later overwritten by the TD which is a subelement so appears on top of the TR.

Also you can combine your css like so:

$('tr:first td').css({
           'font-style':'italic',
           'color':'red',
           'background-color':'yellow'}
);

$('.aTable tr:first td').css({
           'font-style':'italic',
           'background-color':'yellow'}
);

And technically the first selector also catches the second table's first row.

Upvotes: 3

lapin
lapin

Reputation: 2148

This is because of CSS priority, the color is applying to tr, which means that the td { color:blue } is heavier and thus applies. Applying the style to the td inside the tr is one possible solution :

$( "tr:first td" ).css( "color", "red" );

See the jsfiddle.

Upvotes: 2

Related Questions