peter456 peter456 - 1 year ago 61
HTML Question

Displaying an object within an array through DOM

var products = [{
"name": "Lusicious Jello Mix",
"description": ["Very Elegant", "Trending item", "Come in Purple"],
"price": 80.65
}, {
"name": "Tarnished Standing Desk",
"description": ["Modular", "Works for both Tall and Loud People", "Smells like Productivity"],
"price": 1654.99
}, {
"name": "Hand-made Hand Grenades",
"description": ["Such gift!", "Much boom!", "Very safe for kids"],
"price": 10.44
}, {
"name": "Pan-fried Cookie Dough",
"description": ["Chocolate", "Family-size", "Hot Mess"],
"price": 16.99
}, {
"name": "Fancy Dress Hanger",
"description": ["Keep organized", "On Sale"],
"price": 67.32
}, {
"name": "Snarky Britsh Mustache 3-Pack",
"description": ["Sharing is caring!", "Hugs not drugs", "As seen on 'So You Think You Can Dance - Nigeria!'"],
"price": 1.99
}, ];

for (var x=0; x<products.length; x++){
var prodname = document.createElement("h3");
prodname.innerHTML = products[x].name;
var listname = document.getElementById("name");

var proddesc = document.createElement("h3");
proddesc.innerHTML = products[x].description;
var listdesc = document.getElementById("description");

var prodprice = document.createElement("h3");
prodprice.innerHTML = products[x].price;
var listprice = document.getElementById("price");

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Shopping Cart</title>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/styles.css"></link>
<div id="shopHead"><h3>Shopping Cart<h3/>
<h3 id="name"></h3>
<h3 id="description"></h3>
<h3 id="price"></h3>



This is my object within an array called products. By which I am using an array and then using the DOM to display in my HTML page. However it is not coming out in order. I want to display the name in the array at position 0 and then the description at position 0 finally the priced at position 0. Instead it's displaying all my names followed by all of the description followed by all of the prices. It's a simple fix I'm sure but I'm stuck.

Answer Source

Try this

var displayBox = document.createElement("h3");
displayBox.innerHTML = products[x].name + " "+ products[x].description + " "+products[x].price;
var listname = document.getElementById("name");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download