views:

298

answers:

4

Hello

I am facing the following problem: I have a HTML document where I want to print basic status/debug/etc messages.

So, the HTML document contains an empty pre-element whose id is out:

<body onload='init () && main();'>

<pre id='out'>
</pre>

</body>
</html>

The init() function assigns the pre element to a variable:

  var out_div;

  function init() {
      out_div = document.getElementById('out')
      return 1;
  }

Then, in order to print something into the pre-div, I use this function:

  function txt_out(txt) {
      out_div.innerHTML += "\n" + txt
  }

The newline should make sure that each invocation of txt_out is written on its own line. This works as expected in Firefox. IE however doesn't seem to pay attention to the \n. So, is this wrong on IE's part, or am I doing something wrong?

A: 

Change your code to:

function txt_out(txt) {
      out_div.innerHTML += "<br />" + txt
  }
Nicolas Webb
A: 

Change to <br />

Py
+5  A: 

This is a known problem in Internet Explorer. As a workaround, insert a <br> element instead of a newline character.

Jordan Ryan Moore
Exactly. Nice link.
Crescent Fresh
@BalusC — pre elements do **not** contain CDATA, and br is not on the list of excluded child elements ( http://www.w3.org/TR/html4/struct/text.html#h-9.3.4 ). Why do you think that a br element won't work?
David Dorward
+2  A: 

Doing things like element.innerHtml += something; is usually a bad practice because it makes the browser re-parse the entire contents of the element. As you add more and more data, every time it gets slower and slower. It also invalidates any references/event listeners that other pieces of code might have on its sub-elements.

Better use a div tag; something like:

<div id='out'></div>

and then append new sub-elements on the fly:

out_div = document.getElementById('out');

// add a new message
new_element = document.createElement('div');
new_element.textContent = "your message here";
new_element.className = "some_class"; // CSS class for changing the appearance
out_div.appendChild(new_element);
intgr
Oops! Fixed JavaScript errors in my answer.
intgr