This page shows a example of how to change a element's style with JavaScript.
Press the following buttons to change the color.
Color Me
Here's the HTML code:
<p> <span id="id13959">Color Me</span> <button id="b1">RED</button> <button id="b2">BLUE</button> </p>
Here's the JavaScript code:
var xx = document.getElementById("id13959"); var button1 = document.getElementById("b1"); var button2 = document.getElementById("b2"); button1.addEventListener("click", function () {xx.style.color="red";} , false); button2.addEventListener("click", function () {xx.style.color="blue";} , false);
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 JavaScript when should the change happen.
In general, if your CSS attribute is “some-thing”, the JavaScript's attribute name should be like this: ‹ele›.style.someThing="value". Example:
| CSS | JavaScript |
|---|---|
padding:50em | ‹ele›.style.padding="50em" |
border:thin black dashed | ‹ele›.style.padding="thin black dashed" |
background-color:red | ‹ele›.style.backgroundColor="red" |
font-size:large | ‹ele›.style.fontSize="large" |
font-family:"Arial Unicode MS","DejaVu Sans",sans-serif | ‹ele›.style.fontFamily='"Arial Unicode MS","DejaVu Sans",sans-serif' |
CSS's pseudo selectors (⁖ a:visited, a:link, div.nav:before,
div.nav:first-child) cannot be scripted. You can use JavaScript to script the CSS
source code itself, but that is not widely supported.
thanks to NTTalex for a correction.