Internet Explorer, <pre> tags and setting innerHTML

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Internet Explorer, <pre> tags and setting innerHTML

Post by Chris Corbyn »

Code: Select all

<html>
<head>
  <title>IE preformatted text sucks</title>
</head>
<body> 
  <pre id="test">
a b c
d e f
  </pre>
  <script type="text/javascript"><!--
  var textContent = document.getElementById("test").innerText;
  textContent = textContent.replace("a", "<span style=\"color:red;\">a</span>");
  document.getElementById("test").style.whiteSpace = "pre";
  document.getElementById("test").innerHTML = textContent;
  --></script> 
</body>
</html>
Notice if you run that code that although it correctly highlights the "a" character, the <pre> tag loses all formatting in IE. This works as expected in FF, Safari, iPhone and Opera. But in IE6 (the only IE I could test in) it ends up on one line.

Anyone know that solution that DOESN'T involve replacing the whitespace with HTML <br> &nbsp; etc? I don't want to have to encode all spaces, tabs and newlines into HTML since that defies the point of the <pre> tag ;) It would also be way too slow for what I'm doing.

I really hate IE :(
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Internet Explorer, <pre> tags and setting innerHTML

Post by Chris Corbyn »

I'm pretty sure this can't be solved so I had to tackle my problem differently... by using:

[js]preElement.innerHTML = '';preElement.appendChild(aContainerSpanElement);[/js]

I'll be posting another thread shortly with what I've been working on. It's fun :)
Post Reply