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?
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 .
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.
The usual approach is to convert single newlines in the input to “<br />”. (Double-newlines would normally introduce a new “<p>” element.)
Setting innerHTML is synchronous, as are most changes you can make to the DOM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With