-1

For example given something like this

const stuff = [{"a": "b"}]
const inhtml = document.querySelector(".exists")
const pre = document.createElement("pre")
pre.appendChild(document.createTextNode(stuff))
inhtml.appendChild(pre)

I want it to output the array [{"a": "b"}] in a code block dynamically

Except it just outputs [Object object ...]

name
  • 235
  • 2
  • 12

1 Answers1

0

You can use JSON.stringify() to display the text:

const stuff = [{"a": "b"}];
const inhtml = document.querySelector("div#main");
const pre = document.createElement("pre");
const code = document.createElement("code");

code.innerHTML = JSON.stringify(stuff, null, '\t');
code.style.backgroundColor = '#ebccca';

pre.appendChild(code);

inhtml.appendChild(pre);
<p>Code goes below here</p>

<div id="main"></div>
Brian Lee
  • 17,904
  • 3
  • 41
  • 52