user1757641 user1757641 - 1 month ago 6
CSS Question

JS Object formatting in html issue

I have a function that renders an object in html.

for (var i = 0; i < foodItems.length; i++) {
document.getElementById("menuContainer").innerHTML += '<div class="item"> <img src="' + foodItems[i].image + '" >';
document.getElementById("menuContainer").innerHTML += '<h4> ' + foodItems[i].name + '</h4>';
document.getElementById("menuContainer").innerHTML += '<h5> $' + foodItems[i].price + '</h5>';
document.getElementById("menuContainer").innerHTML += '</div>';
console.log("Item: " + foodItems[i].name + " Cost: $" + foodItems[i].price);
}


I seem to be missing a formatting issue. The JS compiles properly, no errors, but both the h4 tag and the h5 tag render outside the div, even though in code the closing div tag is after the h4 and h5 tags.
Here is the HTML after it gets rendered in the browser

<div class="menuHolder" id="menuContainer">

<div class="menuHolder" id="menuContainer">
<div class="item">
<img src="images/hamburger.jpg"></div>
<h4> Hamburger</h4>
<h5> $2.99</h5><div class="item">
<img src="images/fries.jpg"></div>
<h4> Fries</h4>
<h5> $1.99</h5>
<div class="item">
<img src="images/donuts.jpg">
</div>
<h4> Donuts</h4>
<h5> $0.99</h5>
</div>


And here is the css
.item{
padding: 10px;
margin: 20px;
display: inline-block;
position: relative;
border: 1px solid #666;
background: #ddd;
}

.item h4{
font-size: 18px;
text-align: center;
}

.item h5{
font-size: 14px;
text-align: center;
}

.item img{
width: 200px;
height: 200px;
}

Answer

Try this:

for (var i = 0; i < foodItems.length; i++) {
    var tmpstr = '<div class="item"> <img src="' +  foodItems[i].image + '" >';
    tmpstr += '<h4> ' +  foodItems[i].name + '</h4>';
    tmpstr += '<h5> $' +  foodItems[i].price + '</h5>';
    tmpstr += '</div>';
    document.getElementById("menuContainer").innerHTML = tmpstr;
    console.log("Item: " + foodItems[i].name + " Cost: $" + foodItems[i].price);
}

When you added string to innerHTML, browsers may "auto correct" the html and added at the end.

P.S. you may need to take care of escaping characters in your foodItems[i].name.

Comments