2

I need to create a CSS stylesheet class dynamically using JavaScript in IE8.

I have used following code for other browsers:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

it's working fine in all browsers except IE8. How to achieve the same in IE8?

Regent
  • 5,116
  • 3
  • 20
  • 35
Akbar Basha
  • 1,128
  • 1
  • 14
  • 38

1 Answers1

3

According to MSDN:

The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.

So, try to use innerText to write these class.

Updated:

You can use:

style.styleSheet.cssText = '.cssClass { color: #F00; }';

Or do a test:

if (style.styleSheet){
    style.styleSheet.cssText = '.cssClass { color: #F00; }';
} else {
    style.appendChild(document.createTextNode('.cssClass { color: #F00; }'));
}

Hope, it now runs! :)

Radonirina Maminiaina
  • 6,840
  • 4
  • 33
  • 58
  • Ok, wait for a while! – Radonirina Maminiaina May 07 '15 at 11:40
  • @ Radonirina Maminiaina i have used css like this var text = ".highlightStyle { fill:" + fill + ";opacity:" + opacity + ";stroke:" + strokeColor + ";stroke-width:" + strokeWidth + "+ }"; fill , opacity, strokeColor and strokeWidth are variable which changed dynamically... those attributes are working fine in all browser except IE8 in IE8 fill , strokeColor,strokeWidth, opacity properties are not working – Akbar Basha May 07 '15 at 11:57
  • IE8 is a very old browser, but you can see this link: https://css-tricks.com/snippets/css/cross-browser-opacity/ for the opacity – Radonirina Maminiaina May 07 '15 at 12:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/77187/discussion-between-radonirina-maminiaina-and-akbar-basha). – Radonirina Maminiaina May 07 '15 at 12:05
  • @ Radonirina Maminiaina sure – Akbar Basha May 07 '15 at 12:06