Creating Style Tag with JavaScript and Adding Rules to It

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.

Advertisements

One comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s