Display JavaScript object in HTML | Example code

  • by

You can Display JavaScript object in HTML using innerHTML and getElementById, but this will show output as [object Object].

document.getElementById("demo").innerHTML = data;

Using dot in properties of an object to display as a string.

const person = {
  name: "John",
  age: 30,
  city: "New York"
};
var name = person.name;

Display JavaScript object in HTML

Simple example code.

<!DOCTYPE html>
<html>

<body>
  <div id ="demo"></div>
  <script>
   const person = {
    name: "John",
    age: 30,
    city: "New York"
  };

  var text = person.name + "," + person.age + "," + person.city;
  document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output:

Display JavaScript object in HTML

Displaying the Object in a Loop

You can use for loop to collect the properties of an object.

<body>
  <div id ="demo"></div>
  <script>
   const person = {
    name: "John",
    age: 30,
    city: "New York"
  };

  let txt = "";
  for (let x in person) {
    txt += person[x] + " ";
  };

  document.getElementById("demo").innerHTML = txt;
</script>

</body>

Output: John 30 New York

Using JSON.stringify()

If you want show object show as string then use this method.

<!DOCTYPE html>
<html>

<body>
  <div id ="demo"></div>
  <script>
   const person = {
    name: "John",
    age: 30,
    city: "New York"
  };

  let myString = JSON.stringify(person); 
  document.getElementById("demo").innerHTML = myString;
</script>

</body>
</html>

Output: {“name”:”John”,”age”:30,”city”:”New York”}

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.