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?
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.
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]);
}
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