Change background color on button click in javascript is a good example of DOM manipulation.
You can change the background color of any element like div, paragraph or can change the color of the HTML body.
To change the background color we use style property.
Let us see one by one
Changing the background color of the HTML element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> #one{ width:90%; height:50px; border: solid 1px; margin-top:10px; } </style> <script> function changeColor(){ var div1=document.getElementById("one"); div1.style.background="red"; } </script> </head> <body> <input type="button" onclick="changeColor()" value="Change"> <div id="one"></div> </body> </html> |
Changing the background color of the body
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html> <head> <title>Page Title</title> <script> function changeBodyColor(){ document.body.style.background="red"; } </script> </head> <body> <input type="button" onclick="changeBodyColor()" value="Change"> </body> </html> |