Is there a good way to iterate through an array of objects and apply those properties to multiple html elements with same classname?
I hope my example show more specific what I am trying to achieve. Thanks in advance!
var myObject = [{
width: 100,
text: "Hello World",
bgColor: '#f00',
},
{
width: 20,
text: "Hi World",
bgColor: "#0f0",
}
];
const divs = document.getElementsByClassName("one");
console.log(divs);
myObject.forEach(function (arrayItem) {
var x = arrayItem.width;
var y = arrayItem.text;
var z = arrayItem.bgColor;
divs.style.width = x + '%';
divs.innerHTML = y;
divs.style.backgroundColor = z;
});
.contain {
width: 500px;
height: 100px;
background: #666;
padding: 20px;
}
.one {
width: 100%;
height: 50px;
background: #aaa;
display: flex;
align-items: center;
}
.one:first-child {
background: #ddd;
width: 80%;
}
span {
margin: 0 20px;
}
<div class="contain">
<div class="one"><span>Should only read "Hello World", have red background and 100% width.</span></div>
<div class="one"><span>Should only read "Hi World", have green background and 20% width.</span></div>
</div>