Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show console.log() in an HTML element in JavaScript

I programmed a function, which writes all the stuff in the console (with console.log(string);).

Now I want to "simulate" or show the generated console log in a <p> or a <div>.

Does anyone have an idea how to do this?

like image 504
balex Avatar asked Oct 20 '25 11:10

balex


2 Answers

From the clues in your question I take it you work in a browser environment.

console is an object on the window object. Therefor you can easily replace it. The following code will replace the browser's window.console with a custom window.console which has the method log. The log method will take a string and append it to an element with the id myLog

In your HTML:

<p id="myLog"></p>

In your JS:

window.console = {
  log: function(str){
    var node = document.createElement("div");
    node.appendChild(document.createTextNode(str));
    document.getElementById("myLog").appendChild(node);
  }
}
console.log('hi');
console.log('there');

This is given that you only log strings. If you log other things, such as object, you probably want to add a type check in the log method and if it's an object, run it through JSON.stringify before adding it to the node.

like image 135
Emil Oberg Avatar answered Oct 23 '25 00:10

Emil Oberg


HTLM:

<body>
  <ul id ="list"></ul>
</body>

JAVASCRIPT:

function createMessage(str) {
  var newMessage = document.createElement('li').innerHTML = str;
  var list = document.getElementById("list");
  list.insertBefore(newNode, list.childNodes[0]);
}
like image 34
Javi Alcantara Avatar answered Oct 23 '25 00:10

Javi Alcantara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!