If you enjoyed this site, please consider donating $3. Any amount is appreciated. Thanks!

Changing a Element's Style with JavaScript

This page shows a example of how to change a element's style with JavaScript. Press the following buttons to change the background color.

Make the above paragraph: RED me YELLOW me

The javascript code looks like this:

var o = document.getElementById("t");

function f1() {o.style.backgroundColor="red";}
function f2() {o.style.backgroundColor="yellow";}

document.getElementById("b1").onclick = f1;
document.getElementById("b2").onclick = f2;

This technique can be used to change the css value for any html element. All you need to do is to give the html tag a “id”, and define in js when should the change happen.


Related essays:

2006-02
© 2006 by Xah Lee.