2

I'm pulling a bit of html and css from a database, and it happens to contain a bit of css wrapped in a style tag. I then set some innerhtml to the string variable and display it.

The html is rendered properly, but ie will not display the content with the css - of course firefox will. Below is an abbreviated example of the code

var outputString = '<style type="text/css">.fontRed{color:red;}</style><span class="fontRed">red</span>'

I then set it to the innerHTML

document.getElementById('bilbo').innerHTML = outputString;

This displays properly (the color red) in FF, however does not in IE. Is there a character I need to escape for IE? The rest of the html works, and even inline styles work correctly in IE.

Any assistance would be most welcome.

Thanks

3
  • Would help if you described what it did do in IE. BTW, using a style like .fontRed {color:red;} completely misses the point of CSS. Commented Nov 6, 2012 at 21:47
  • Im giving a brief code snippet. The outputString is set to the CLOB pulled from the db, which in this case is a text filled web page explaining something. I am wanting to display the page as is. It displays properly in FF and not in IE, aka the css part does not render in IE. Commented Nov 6, 2012 at 22:11
  • The code pulled is not a web page that I wrote, it is actually nothing but a huge pile of text for a user agreement. So I have to work with what I am given...The code in IE renders without the css, in the example the text would be black, and not red. IE Does NOT recognize anything between the style tags Commented Nov 6, 2012 at 22:24

3 Answers 3

1

Try this Approach .. Tested in IE7 and above

// Create the Style Element
var styleElem = document.createElement('style');
styleElem.type = 'text/css' ;

var css = '.fontRed{color:red;}' ;

if(styleElem.styleSheet){
    styleElem.styleSheet.cssText = css;
}
else{
    styleElem.appendChild(document.createTextNode(css));
}

// Append the Style element to the Head
var head = document.getElementsByTagName('head')[0] ;
head.appendChild(styleElem);

// Append the span to the Div 
var container = document.getElementById('bilbo');
container.innerHTML = '<span class="fontRed">red</span>' ;​

Check FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

1

Append the <style type="text/css">.fontRed{color:red;}</style> to the head tag first.

Comments

0

Just put <body> at the start of the output string. i.e.

document.getElementById('bilbo').innerHTML = '<body>' + outputString;

See http://jsfiddle.net/ScEZ4/1/ for a working demo.

Tested and working IE6, IE7, IE8, IE9, FF16, Chrome22, Opera12

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.