Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: console.log to html

Tags:

javascript

I would like to write the console.log output to a div layer.

For example:

document.write(console.log(5+1)); //Incorrect, random example 

Can someone give me a solution to my problem?

Thank you.

EDIT:

what i meant is, for example:

console.log("hi"); 

and it shows the output "hi" on the screen.

Note: An example: http://labs.codecademy.com/#:workspace

like image 751
leonneo Avatar asked Nov 28 '13 02:11

leonneo


People also ask

Can we use console log in HTML?

The console. log() method in HTML is used for writing a message in the console. It indicates an important message during testing of any program. The message is sent as a parameter to the console.

How do I print a console log?

log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console. log(A);


2 Answers

You can override the default implementation of console.log()

(function () {     var old = console.log;     var logger = document.getElementById('log');     console.log = function (message) {         if (typeof message == 'object') {             logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';         } else {             logger.innerHTML += message + '<br />';         }     } })(); 

Demo: Fiddle

like image 94
Arun P Johny Avatar answered Oct 02 '22 21:10

Arun P Johny


Slight improvement on @arun-p-johny answer:

In html,

<pre id="log"></pre> 

In js,

(function () {     var old = console.log;     var logger = document.getElementById('log');     console.log = function () {       for (var i = 0; i < arguments.length; i++) {         if (typeof arguments[i] == 'object') {             logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';         } else {             logger.innerHTML += arguments[i] + '<br />';         }       }     } })(); 

Start using:

console.log('How', true, new Date()); 
like image 22
Nitin... Avatar answered Oct 02 '22 21:10

Nitin...