DESIGN:
I use in-line style sheets with the <style> tag fairly often, so that's what I used for my experiment. To support this I put an empty set of style tags in my page header. Since this is an experiment and I want reusable code for bigger projects, I decided to use a function to make the changes. My function, change_style, takes the desired style in CSS syntax as an argument which it sets as the content between the opening and closing style tags by assigning it to document.getElementsByTagName('style')[0].innerHTML.
For experimental purposes, I decided to use buttons to trigger the changes. I created four buttons which call my function with different arguments, including one that sets the style back to empty.
CODE:
My final code looked like this:
<html>
<head>
<title>Changing style</title>
<style type="text/css">
</style>
<script type="text/javascript">
function change_style(new_style){
document.getElementsByTagName('style')[0].innerHTML=new_style;
}
</script>
</head>
<body>
<p>Press Button to Change Style</p>
<form>
<input type="button" value="Font Color" onclick="change_style('body{color: teal;}')">
<input type="button" value="Font Size" onclick="change_style('body{font-size:30;}')">
<input type="button" value="Background" onclick="change_style('body{background: pink;}')">
<input type="button" value="Default" onclick="change_style('')">
</form>
</body>
</html>
DISCUSSION:
This works well, but it quickly gets unwieldy as you have more style information. I think using external style sheets would be a better solution in this case. Using the style tag seems more useful for adding or changing one or two items in the style sheet. Taking advantage of the cascading feature of CSS , this can be done by simply changing the function to use the concatenation operator (.=) to append new information to the contents between the style tags.
This results in the following function:
function change_style(new_style){
document.getElementsByTagName('style')[0].innerHTML.=new_style;
}
In both cases, we are assuming we have one and only one set of style tags in the document. That seems like a reasonable assumption, but what if you had different style sheets for printing versus screen use? How do you know you are changing the correct one?
REFERENCE:
Style Sheets in HTML documents - from the W3C