Reputation: 5138
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>
Upvotes: 4
Views: 15064
Reputation: 10489
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'});
});
Upvotes: 2
Reputation: 9002
Use $(document).ready()
:
$(document).ready(function(){
$('.myClass td').css({'background-color': 'yellow'});
});
See jsfiddle for working example.
Upvotes: 3
Reputation: 4278
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
Upvotes: 0
Reputation: 8978
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.
Upvotes: 2
Reputation: 6522
Use document.ready for your JS.
$(document).ready(function(){
$('.myClass td').css({'background-color': 'yellow'});
});
Upvotes: 4