Hello guys! I have been trying an exercise to change the background color of 5 boxes to different colors. So, I thought I could use the rgb() to do it. For that, I created an array of random values from 0 to 255 of length 15. I thought I could pass RGB values as variables and do the task, BUT its not working. So to check if its variable error or syntax, i tried to pass rgb with values and it worked. Can you guys help me with it and tell me what i’m doing wrong and tell me how to correct it please
please post your code, don’t post a screenshot of code
Sure.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color the Boxes Assignment - 12 | Day - 70</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
gap: 23px;
}
.box {
display: flex;
justify-content: center;
align-items: center;
width: 45px;
height: 45px;
border: 2px solid black;
}
</style>
</head>
<body>
<!--
Given 5 boxes, Assign a random color and a random background to each box using DOM concepts
-->
<div class="container">
<div class="box">Box</div>
<div class="box">Box</div>
<div class="box">Box</div>
<div class="box">Box</div>
<div class="box">Box</div>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript
let bg_color = [];
let color = [];
for (let i = 1; i <= document.body.children[0].children.length*3; i++) {
bg_color.push(Math.floor(Math.random() * 255 + 1));
color.push(Math.floor(Math.random() * 255 + 1));
}
console.log(bg_color);
console.log(color);
let e = 0;
for (let i = 0; i < document.body.children[0].children.length; i++) {
document.body.children[0].children[i].style.backgroundColor = "rgb(bg_color[e], bg_color[e + 1], bg_color[e + 2])";
console.log(bg_color[e], bg_color[e + 1], bg_color[e + 2])
// console.log(e);
e += 3;
}
you need to use a template literal here, if you want to interpolate variables inside the string
2 Likes
Thanks alot @im59138, it worked!!!
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.