-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 ...]

5
  • 1
    one problem is that code never uses the variable stuff Commented Aug 20, 2020 at 22:28
  • You can use JSON.stringify(obj) to help convert an object into a string. Commented Aug 20, 2020 at 22:29
  • oh that works! Is there a way to format it properly as well @PotatoParser Commented Aug 20, 2020 at 22:31
  • 1
    Yes! You can do JSON.stringify(obj, null, '\t') which will automatically tab key/values on the inside! Commented Aug 20, 2020 at 22:34
  • That's EXACTLY what i wanted thank you Commented Aug 20, 2020 at 22:36

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, that worked. Is there a way to format it also
You can format the output using CSS.
@shah I've updated the answer.
Oh, so there is no way to color code basic javascript color in the code block without css?
You can use javascript to set the style attributes. I've changed the answer to show how.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.