Faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 16 people (94%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How do I append a CSS rule set to the page?

Sep 29th, 2001 02:17
Martin Honnen,


The following code works with IE4+ and NN6 if there already is a 
  <style type="text/css"></style>
element (empty as above or with some rules) in the document. Then the 
passed in rule is added as the last rule to the last style sheet in the 
document so that it should be the last in the CSS cascade to apply.
If there is no style sheet in the document the code attempts to add a 
style element. This works with IE5+ but not with IE4, and it doesn't 
work with NN6(.0, .01, .1) although it should work. Therefore the 
example page below contains an empty style element to allow the code to 
work:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
adding style rules
</title>
<style type="text/css"></style>
<script type="text/javascript">
function appendStyleRule (ruleSet) {
  if (document.styleSheets) {
    if (document.styleSheets.length == 0) {
      appendStyleElement();
    }
    if (document.styleSheets.length > 0) {
      if (document.styleSheets[0].insertRule) {
        document.styleSheets[document.styleSheets.length -1 
].insertRule(ruleSet, document.styleSheets[document.styleSheets.length - 
1].cssRules.length);
      }
      else if (document.styleSheets[0].addRule) {
        var ruleSetPattern = /(.*)({([^}]*)})/;
        var match = ruleSetPattern.exec(ruleSet);
        if (match) {
          var selector = match[1];
          var declarations = match[3];
          document.styleSheets[document.styleSheets.length 
-1].addRule(selector, declarations);
        }
      }
    }
  }
}
function appendStyleElement () {
  if (document.createElement) {
    var styleElement = document.createElement('style');
    if (styleElement) {
      styleElement.type = 'text/css';
      var headElement = document.getElementsByTagName('head')[0];
      headElement.appendChild(styleElement);
    }
  }
}
</script>
</head>
<body onload="appendStyleRule(
'body { color: green; background-color: yellow}');
              appendStyleRule(
'p { color: orange; border: 3px solid orange;}')">
Kibology
<p>All for Kibology</p>
</body>
</html>