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
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
Share Improve this question asked Aug 4, 2009 at 1:24 madphpmadphp 1,7645 gold badges31 silver badges72 bronze badges 3- What do you mean by change CSS? – Marius Commented Aug 4, 2009 at 1:27
- 1 Mark -- you're in the right place. Welcome :-) – Josh Commented Aug 4, 2009 at 3:00
- sorry. meant to say elements style. – madphp Commented Aug 4, 2009 at 13:26
2 Answers
Reset to default 9Yes, 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"});
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">google</a>
document.getElementById("link").setAttribute("href", "http://www.stackoverflow.com");