views:

789

answers:

2

Can this be used to change CSS? Cant see much on w3 about it. Anyone know anything about it.

If this forum/site isnt the place for asking browser standard questions, can someone point me in the right direction?

Thanks

--Mark

+1  A: 

Not sure what you mean. If you want to set a CSS value, for example background color, then you have to set that on some element, for example the body:

document.body.style.backgroundColor = "#FF0000";

If you want to change the CSS stylesheet, then you can use the styleSheets object:

document.styleSheets[0].cssRules[0].backgroundColor = "#FF0000";

setAttribute is used to set the attribute of some html element, for example the href in an anchor element:

<a id="link" href="http://www.goolge.com"&gt;google&lt;/a&gt;



document.getElementById("link").setAttribute("href", "http://www.stackoverflow.com");
Marius
A: 

Yes, you can use setAttribute to change the CSS of a single DOM element, like so:

document.getElementById("something").setAttribute("style", "color: red;");

However, I believe it's bad practice. You can modify the stylesheet as Marius pointed out by doing:

document.styleSheets[0].cssRules[0].backgroundColor = "#FF0000";

or by manually editing the style attributes of HTML elements, like:

document.body.style.backgroundColor = "#FF0000";

I would recommend looking into jQuery, as it has powerful and easy to use tools for modifying the CSS of DOM elements. It's as simple as:

$("#someID").css({"color": "red", "width": "100px"});
Mike Trpcic
thanks. That is what i was thinking. Hasnt document.stylesheets been removed from the w3 standards?
madphp