I am working on a game and have run into a problem that I have been stuck on for hours. I have an object, and I want to write a loop which will take all the values in this object, and stick them into an html div. The way I am doing this is, I have taken a div, I am cloning it and giving all the child elements new values. Then I want to use the DOM manipulation to insert the values from one key, into a div with a heading and two paragraphs. Here is the code.
Index.html
<div id = "all_asset" style = "display: none;"> <div class = "touch_box col-sm-12" style = "height: 150px; display: none;" id = "asset_touchbox"> <br><h id = "asset_name"></h> <p1 id = "asset_price"></p1><hr> <p id = "asset_age"></p><hr> </div> </div> play.js
function assetsList(){ Object.keys(assets).forEach(key => { for (var i = 1; i < Object.keys(assets).length; i++){ //duplicate box var list_box = document.getElementById("asset_touchbox"); var clone_box = list_box.cloneNode(true); clone_box.id = "list_assets" + String(i); document.getElementById("all_asset").appendChild(clone_box); //get id of child elements clone_box.getElementsByTagName('h')[0].id = "asset_name" + String(i); clone_box.getElementsByTagName('p1')[0].id = "asset_price" + String(i); clone_box.getElementsByTagName('p')[0].id = "asset_age" + String(i); list_box.parentNode.appendChild(clone_box); //show box clone_box.style.display = "block"; var asset_name = assets[key][0]; var asset_age = assets[key][1]; var asset_price = assets[key][2]; document.getElementById("asset_name" + String(i)).innerHTML = asset_name; document.getElementById("asset_price" + String(i)).innerHTML = asset_age; document.getElementById("asset_age" + String(i)).innerHTML = asset_price; } }); } Javascript Object
//asset name, asset age, asset cost assets = {1: ["Boat", 0, "10000"], 2: ["Carriage", 0, "10000"]} So what I pretty much want to do is - Create two divs, each one has the information from each key. I hope I made sense. Please let me know if I didn't. Thanks!
https://stackoverflow.com/questions/66450160/looping-through-javascript-object-and-adding-to-html-div March 03, 2021 at 11:01AM
没有评论:
发表评论