1

This code is from Javascript: console.log to html, I'm trying to figure out how make the new messages go on top rather than one right after the other.

(function() {
    if (!console) {
        console = {};
    }
    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) :
                String(message)) + '\n';
        } else {
            logger.prepend(message) = logger.innerHTML + message;
        }
    }
})(); 

The "logger.prepend(message) = logger.innerHTML + message;" throws a reference error "invalid statement left-hand side"

avaldivi
  • 41
  • 3

3 Answers3

0

Don't know if you're looking for a JS solution, but with CSS the easiest way would be to use position: absolute and bottom: 0 on #log. Demo on this jsfiddle

elveti
  • 2,316
  • 4
  • 20
  • 27
0

The solution above is great, I just don't have enough reputation points to upvote it. If you're looking to get the latest message on top:

    (function() {
    if (!console) {
        console = {};
    }
    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) :
                String(message)) + '\n';
        } else {
            return logger.prepend(message);
        }
    }
})(); 
avaldivi
  • 41
  • 3
0

You need - HTML DOM insertBefore() Method

function myFunction() {
  var newItem = document.createElement("LI");
  var textnode = document.createTextNode("Water");
  newItem.appendChild(textnode);

  var list = document.getElementById("myList");
  list.insertBefore(newItem, list.childNodes[0]);
}
<ul id="myList">
  <li>Coffee</li>
  <li>Tea</li>
</ul>

<p>Click the button to insert an item to the list.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Example explained:</strong><br>First create a LI node,<br> then create a Text node,<br> then append the Text node to the LI node.<br>Finally insert the LI node before the first child node in the list.</p>

Enter your code here console test: https://codepen.io/pedro404/pen/NWbLRLB

Pedro404
  • 158
  • 5