0

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" );
6
  • Your code looks valid, could you try official example? Maybe try step-by-step modifications and watch for differences :) api.jquery.com/first-selector Commented Oct 31, 2014 at 7:13
  • 2
    You change tr color to red, but td still has blue color set. Commented Oct 31, 2014 at 7:14
  • @Justinas thnx changing to $( "td:first" ).css( "color", "red" ) did the job Commented Oct 31, 2014 at 7:15
  • 1
    Your code works perfectly fine. Are you including a link to jQuery? Commented Oct 31, 2014 at 7:15
  • @chipChocolate.py yes jQuery 2.1.0. moreover I want my first row of first table to be red Commented Oct 31, 2014 at 7:16

3 Answers 3

3

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.

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

Comments

2

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.

Comments

0

You need to set as below:

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

DEMO

Comments

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.