4

I am trying to change the background color with jQuery. What am I doing wrong? I know this can be done with CSS a lot easier but I am trying to do it with jQuery.

Link to jsfiddle. I am trying to change the background of "Hi" to yellow.

window.onload=function(){
     $('.myClass td').css({'background-color': 'yellow'}); 
}

<table>
    <tr class="myClass">
        <td>Hi</td>
    </tr>
    <tr>
        <td>Bye</td>
    </tr>
</table>
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Susie
  • 4,740
  • 9
  • 47
  • 72

5 Answers5

4

Use document.ready for your JS.

$(document).ready(function(){
     $('.myClass td').css({'background-color': 'yellow'}); 
});
andi
  • 6,270
  • 1
  • 15
  • 43
3

Use $(document).ready():

$(document).ready(function(){
     $('.myClass td').css({'background-color': 'yellow'}); 
});

See jsfiddle for working example.

Oliver
  • 8,191
  • 2
  • 31
  • 55
2

window.onload is probably being overwritten by something.

Instead try

$(function(){
     $('.myClass td').css({'background-color': 'yellow'}); 
});

Which is shorthand for $(document).ready.

Here is a discussion of the difference between the onload and ready events.

Community
  • 1
  • 1
user1234
  • 5,520
  • 3
  • 25
  • 35
2

Bind your function to jQuery's document.ready event:

$(document).ready(function () {
    $('.myClass td').css({'background-color': 'yellow'});
});

Or, more concisely:

$(function () {
    $('.myClass td').css({'background-color': 'yellow'});
});
kevinji
  • 9,983
  • 4
  • 35
  • 55
0
window.onload=function(){
     $('.myClass td').css("background-color", "yellow"); 
}();

Just added in the (); at the end to invoke it.

http://jsfiddle.net/p2Uwx/5/ <-- updated fiddle

BenM
  • 4,110
  • 2
  • 27
  • 57
  • This does not actually work (at least correctly) in all cases unless your JavaScript is *after* the actual element. Without the `()` is correct, though `window.onload` on jsFiddle is probably being overridden by jQuery. – kevinji Aug 27 '13 at 21:25
  • Yeah I would advise that they use $(document).ready() instead. – BenM Aug 27 '13 at 21:26
  • Thanks for the answer and it worked but I'm just curious, why do we have to add (); at the end? – Susie Aug 27 '13 at 21:27
  • 1
    Hi Susie. This is not best practice, especially when using jQuery, $(document).ready is far more suitable instead of window.onload. As for your question about the (); at the end. When you write out a function in javascript, you are only declaring it. To get it to run you can either call it or if you want it to run straight away after the declaration you can add (); and it will run. It is sometimes called an Immediately Invoked Function Expression or IIFE (iffy) – BenM Aug 27 '13 at 21:29
  • This code is currently equivalent to `$('.myClass td').css("background-color", "yellow");` without `window.onload`, which essentially defeats the purpose of using `$(document).ready` or `window.onload`. – kevinji Aug 27 '13 at 21:32