0

I would like to create a "Console" app for JavaScript so that messages are written to the screen.

console.log("Rerouting log messages to the screen");
console.log = function (message) { document.writeln(message); };
console.log("Log messages are now routed to the screen.");

This works, except that each time something is written to the screen, it wipes out any existing content.

Is there a way to do this?

Greg Gum
  • 33,478
  • 39
  • 162
  • 233

1 Answers1

3

This is how document.write works. To avoid this you should use document.createElement and document.body.appendChild for example.

For example you can try this code:

console.log = function (message) { 
    var p = document.createElement( 'p' );
    p.innerHTML = message;
    document.body.appendChild( p );
};

Read more about document.write at MDN.

antyrat
  • 27,479
  • 9
  • 75
  • 76