Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to show an object in html

I'm trying to show all the data.

const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
document.write(<br> ${key}: ${value});
}

this document.write works, however i had a problem with another program (and here I'm just trying to learn how to show the data in html, console is easy)

let data3 = {
manufacturer: "Focus",
power: "123 bhp",
color: "Red",
year: 2009,
FuelType: "diesel"
};
for (let [key, value] of Object.entries(data3)) {
document.getElementById("carData3").innerHTML = (<br> ${key}: ${value});
// not working
}
btw carData3 is a label.

I even rewrote this just to show what works and what doesnt:-

let data1 = {
manufacturer: "Focus",
power: "123 bhp",
color: "Blue",
year: 2013,
FuelType: "petrol"
};

for (let [key, value] of Object.entries(data1)) {
let y = document.getElementById("carData1");
y.innerHTML= (${key}: ${value}); // Not working
document.write(<br> ${key}: ${value}); // This works
console.log(<br> ${key}: ${value}); // This works
}

Really grateful for any help

P.s carData1 and carData2 are labels and spelled correctly - I think the problem lies in accessing with the DOM but I just can't see it.

1 Answer

Steven Parker
Steven Parker
231,248 Points

Both document.write and console.log create a new line each time they are used. But updating the attribute will overwrite anything that was already there (from a previous pass through the loop), so you will only see the very last thing written.

You can simulate the behavior of the other functions using the concatenating assignment operator:

y.innerHTML += (`<br>${key}: ${value}`); // use += instead of just =

I did a quick test with the DOM last night:- document.getElementById("carData3").style.color = "red"; Just to make sure I was selecting the right element so I narrowed it down to a problem with = (<br> ${key}: ${value}); Still didn't make the connection. I completely missed that, thanks very much.