-2

hello I wanted to if there is way to add a javaScript object inside a html tag but i want it to be a type of object not string.

for more clarification, here is an example :

const codeEl = document.querySelector('div')

let obj = {
    "test": 1,
    "test2": 2
}

codeEl.textContent = JSON.stringify(obj)

the output of the code will be an object with type of string inside an html element. but the thing is that i dont want the object to be converted to a string; i want it actual object type to be displayed inside the html element (for some library usage purposes)

  • I have no idea how you expect the **text** content of an element to render an object as anything other than a string. You need to be clearer about what you expect the output to be. – Quentin Mar 31 '23 at 14:01

1 Answers1

-1

A string is what will be rendered to the DOM, passing an object will either render the object as a string or throw an error (I can't remember which). Stringifying the JSON as you've shown in your example is the correct way to go. Then you can grab the content later and parse it as JSON using JSON.parse() (the documentation for which can be found here.

If I may ask, what's your reason for outputting a variable into the DOM? Is this going to be in a hidden field for access from a different script/library? Is this not something you can handle fully internally inside the script without affecting the DOM?

  • Im using highlight js library and inside a code tag in html, i can write some js codes and it will automaticaly highlight some syntaxes for me. But i dont want to do it manually inside the html tag and i want to be more dynamic using javascript and as i tested, when i use stringify method it wont change the syntax colors – Mohammad Kargar Mar 31 '23 at 14:27