Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<pre> tag loses line breaks when setting innerHTML in IE

I'm using Prototype's PeriodicalUpdater to update a div with the results of an ajax call. As I understand it, the div is updated by setting its innerHTML.

The div is wrapped in a <pre> tag. In Firefox, the <pre> formatting works as expected, but in IE, the text all ends up on one line.

Here's some sample code found here which illustrates the problem. In Firefox, abc is on different line than def; in IE it's on the same line.

    <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>

Anyone know of a way to get around this problem?

like image 670
MCS Avatar asked Jan 16 '09 18:01

MCS


People also ask

Why you shouldn't use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .

What happens when you set the innerHTML of an element?

A string containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

How do you break a line in pre tag?

The usual approach is to convert single newlines in the input to “<br />”. (Double-newlines would normally introduce a new “<p>” element.)

Is setting innerHTML synchronous?

Setting innerHTML is synchronous, as are most changes you can make to the DOM.


1 Answers

Setting innerHTML fires up an HTML parser, which ignores excess whitespace including hard returns. If you change your method to include the <pre> tag in the string, it works fine because the HTML parser retains the hard returns.

You can see this in action by doing a View Generated Source after you run your sample page:

<PRE id="test" style="WHITE-SPACE: pre"><SPAN style="COLOR: red">a</SPAN> b c d e f </PRE>

You can see here that the hard return is no longer part of the content of the <pre> tag.

like image 147
EndangeredMassa Avatar answered Sep 26 '22 02:09

EndangeredMassa