Syntastic
Syntastic

Reputation: 3

How do I make my JS console output as text in HTML

So I want my console output to appear as text in my HTML file but I don't know how. this is the code I have right now: console.log(generateRandom(17));"> I want what this outputs to be text in a HTML file. Can anyone help me?

Upvotes: 0

Views: 1054

Answers (2)

jsejcksn
jsejcksn

Reputation: 33881

This is a problem with some yet-to-be defined behavior. However, if you will only be logging JSON-compatible data types, here's one way to do it:

<!-- This list element will be used to display the console messages -->
<ul id="console-output"></ul>

<!-- Style however you want -->
<style>
  #console-output { list-style: none; }
  .console-message { border-top: 1px solid; }
</style>

<script type="module">
  // The list element used to display your messages:
  const list = document.getElementById('console-output');

  // A function to append new values to the element:
  function print (...values) {
    const listItem = document.createElement('li');
    listItem.classList.add('console-message');
    for (const value of values) {
      const pre = document.createElement('pre');
      const code = document.createElement('code');
      code.textContent = JSON.stringify(value, null, 2);
      pre.appendChild(code);
      listItem.appendChild(pre);
    }
    list.appendChild(listItem);
  }

  // Create a reference to the original console.log method:
  const originalLogMethod = console.log.bind(console);

  // Overwrite it with a custom fn that also invokes the `print` fn above:
  console.log = (...values) => {
    originalLogMethod(...values);
    print(...values);
  };

  // Then just use `console.log` normally in your code:
  console.log('hello');
  console.log('hello', 'world');
  console.log(['it', 'works', 'with', 'arrays']);
  console.log({it: {also: {works: {with: 'objects'}}}});
</script>

Upvotes: 0

JDawwgy
JDawwgy

Reputation: 935

Something like this should do the trick

const text = document.createElement("p");
text.innerText = generateRandom(17);

document.body.appendChild(text);

Upvotes: 1

Related Questions