document.write style css javascript

18,488

Solution 1

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

Solution 2

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

Solution 3

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

Share:
18,488
user1689274
Author by

user1689274

Updated on June 04, 2022

Comments

  • user1689274
    user1689274 almost 2 years

    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