Change background color with jQuery

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

Link to jsfiddle . I am trying to change the background "Hello" 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> 
+4
source share
5 answers

Use document.ready for your JS.

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

Use $(document).ready() :

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

See jsfiddle for a working example.

+3
source

window.onload is probably writing something.

Try instead

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

This is a shorthand for $(document).ready .

This discusses the difference between onload and ready events.

+2
source

Bind your function to the jQuery document.ready event:

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

Or, more briefly:

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

Just added to (); at the end to call it.

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

0
source

Source: https://habr.com/ru/post/1499240/


All Articles