Changing a Element's Style with Javascript

, 2006-02, 2010-10-21, 2011-01-12

Advertise Here

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="xx1">Color Me</span>
<button id="b1">RED</button>
<button id="b2">BLUE</button>
</p>

Here's the js code:

var o = document.getElementById("xx1");
document.getElementById("b1").onclick = function () {o.style.color="red";};
document.getElementById("b2").onclick = function () {o.style.color="blue";};

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.

General Example

In general, if your CSS attribute is “attribName”, you want your js code to be like this: myobj.style.attribName="value". If the attribute name has a hyphen, in JS there should not be hyphen. Here's some examples:

CSSjavascript
{padding:50em}myobj.style.padding="50em"
{border:thin black dashed}myobj.style.padding="thin black dashed"
{background-color:#e8e8e8}myobj.style.backgroundColor="#e8e8e8"
{font-size:large}myobj.style.fontSize="large"
{font-family:"Arial Unicode MS","DejaVu Sans",sans-serif}myobj.style.fontFamily='"Arial Unicode MS","DejaVu Sans",sans-serif'

Pseudo Selectors Cannot Be Scripted

CSS's pseudo selectors (e.g. “a:visited”,“a:link”,“div.nav:before”, “div.nav:first-child”) cannot be scripted. You can use js to script the CSS source code itself, but that is not widely supported.

2011-01-12 thanks to NTTalex for a correction.

blog comments powered by Disqus