-1

So I have an array of objects and I want to display them in order. I want to assign each attribute or property of the object to DOM objects such as "title" to h1 or "description" to p etc. and have each object inside a new div element. I'm sort of new to javascript so I'm really not sure where to start here.

var ads = [
{
    title: "Photo Play Paper Collections",
    description: "Don't miss these brand new Photo Play Paper Collections!",

},
{
    title: "Foil & Foiling Accessories",
    description: "Once you add this color & shine to your paper, wood, fabric, or other porous surfaces you'll want to do it over and over again.",

},
];

When I try to display this

 document.getElementById("test").innerHTML=ads

It just returns as

[object Object],[object Object]

First of all, how to I get it to display the actual information stored, and secondly how would I append each attribute to an element using javascript? Sorry this is sort of vague. The only things I've seen involve using angular or react. Is there a somewhat simple way to do this using only pure javascript?

louisebelcher
  • 99
  • 1
  • 2
  • 16

1 Answers1

1

First of all, how to I get it to display the actual information stored?

You could use JSON.stringify to turn it into the json string representation:

  document.getElementById("test").textContent = JSON.stringify(ads);

and secondly how would I append each attribute to an element using javascript?

That is slightly more complicated. You would have to manually iterate the array and build up your own DOM nodes:

 const parent = document.getElementById("test");

 for(const { title, description } of ads) {
  // Build up new dom nodes
  const headline = document.createElement("h1");
  headline.textContent = title;
  const container = document.createElement("div");
  container.textContent = description;
  // append them:
  parent.appendChild(headline);
  parent appendChild(container);
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151