I'm trying to create this piece of code in which an element is pushed into an array, displayed and get a style added which gives them a random hex color. I got the hex color and the pushing into the array partly done, but I can't seem to be able to add the style nor display the div… Here is my code so far:
JS
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
var elements = []
var el = '<div class="element bg"></div>'
document.getElementById("addEl").onclick = () => {
elements.push(el)
//console.log(elements)
for (i = 0; i < elements.length; i++) {
console.log(elements[i])
document.write(elements[i])
//elements[i].style.backgroundColor = colorBg
}
}
HTML
<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>
CSS
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
document.write. Instead, retrieve the parent element of where you want your elements to be displayed and thenparent.innerHTML += el