Creating Style Tag with JavaScript and Adding Rules to It

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

Sometimes, when working with dynamically created objects on the client, it is needed to style these elements in a specific way. Due to the nature of these objects (for example – unique IDs) , they cannot be styled in the classic way, though. The document.createElement method of JavaScript can be used to create <style>...</style> tag and append it in the <head>...</head> section of the page, however populating it with CSS rules / classes cannot be done with innerHTML under Internet Explorer, which implements a different method for this particular case – by applying the cssText method to the styleSheet object.

Below is an example of how to implement this approach.

function createStyleTag()
 {
  var head = document.getElementsByTagName('head')[0];
  var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
  var cssstring = [
   '#MyDiv1 {' +
    'color: red;' +
   '}'
  ];
  if(!isChrome && !isSafari)
  {
   var styletag = $create('style');
   
   styletag.setAttribute('type', 'text/css');
   head.appendChild(styletag);
   
   if(!window.ActiveXObject)
   {
    styletag.innerHTML = cssstring; // if not Internet Explorer
   }
   else
   {
    styletag.styleSheet.cssText = cssstring; // if Internet Explorer
   }
  }
 }

The full example is available for download at this link.

Categories and Tags
Links

© 2006 - 2023 Martin Ivanov