xxxxxxxxxx
<!DOCTYPE html>
<html>
<head>
<title>Console Log in HTML</title>
<script>
// Save the original console.log function
const originalConsoleLog = console.log;
// Override console.log to capture logs
console.log = function(message) {
// Create a new paragraph to display the log
const logElement = document.createElement("p");
logElement.textContent = message;
// Append the log element to a specific div or the body
const outputDiv = document.getElementById("logOutput");
outputDiv.appendChild(logElement);
// Call the original console.log function
originalConsoleLog.apply(console, arguments);
};
</script>
</head>
<body>
<!-- The log output will be appended to this div -->
<div id="logOutput"></div>
<!-- Scripts that perform some console log statements -->
<script>
console.log("Hello, world!");
const x = 42;
console.log("The value of x is:", x);
</script>
</body>
</html>
xxxxxxxxxx
(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 />';
}
}
})();
xxxxxxxxxx
// DevTools: to console log as <div> element, not as ▶ div#myDiv object
const divEl = document.querySelector('#myDiv');
onload = (e) => console.log(divEl); // <div id="myDiv"></div>
// use 'onload' event handler property to wait for page to load then
// console log, allowing the blink engine to find the 'nodeId', otherwise
// its unpredictable and my print randomly one or the other
console.log(divEl)
// <div id="myDiv"></div>
// ▶ div#myDiv -> didnt find nodeId, so prints object
xxxxxxxxxx
(function (logger) {
console.old = console.log;
console.log = function () {
var output = "", arg, i;
for (i = 0; i < arguments.length; i++) {
arg = arguments[i];
output += "<span class=\"log-" + (typeof arg) + "\">";
if (
typeof arg === "object" &&
typeof JSON === "object" &&
typeof JSON.stringify === "function"
) {
output += JSON.stringify(arg);
} else {
output += arg;
}
output += "</span> ";
}
logger.innerHTML += output + "<br>";
console.old.apply(undefined, arguments);
};
})(document.getElementById("logger"));
// Testing
console.log("Hi!", {a:3, b:6}, 42, true);
console.log("Multiple", "arguments", "here");
console.log(null, undefined);
console.old("Eyy, that's the old and boring one.");