Search code examples
javascriptjqueryhtmlinternet-explorer-8pre

code inside pre goes in one line on IE8


I'm trying to take the value from a textarea and put it inside a pre tag, and it works ok on chrome and mozilla but on IE8 the entire content stays on one line in the pre tag

jsbin link: http://jsbin.com/uwunug/4/edit

this is the whole thing:

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

</head>
<body>
<script type='text/javascript'>
$(function(){

$('#b1').click(function(){
x = $('textarea').val();
$('#tt').html(htmlEscape(x));    
});

});
function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')            
            .replace(/>/g, '&gt;');
}
</script>


 <textarea cols='50' rows='20'>
 </textarea>
 <button id='b1'>make code</button>
 <pre class="prettyprint" id='tt'>
</pre>

</body>
</html>

I noticed (by replacing \n to 'enter') the \n chars go into the pre but they don't produce new line in there


Solution

  • "IE applies HTML normalization to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>."

    Inserting a newline into a pre tag (IE, Javascript)

    The \n solution is probably going to be your best shot (the only other option is to use innerText it seems, but I prefer your solution).