Diasline
Diasline

Reputation: 635

Change div background color according to list of array

How can I apply the background color found in array to each div of class name rectangle.

<div id="rectangleWrapper">

<div id="rectangle-1">

</div>
<div id="rectangle-2">

</div>
</div>

const rectWrapDiv = document.getElementById("rectangleWrapper").children;
for (const prop of rectWrapDiv){
prop.classList.add("rectangle");
}

const bcgColor = ["red", "blue" ];
for (let i = 0; i < rectWrapDiv.length; i++){

for (let j = 0; j < bcgColor.length; j++){
    rectWrapDiv[i].style.background  = bcgColor[j];
console.log(bcgColor[j])
}

}

When I diplay it in console browser only the index 1 is taken as background to all divs.

Upvotes: 0

Views: 493

Answers (3)

D. Seah
D. Seah

Reputation: 4592

you can use querySelectorAll

const bcgColor = ["red", "blue" ];
document.querySelectorAll("#rectangleWrapper div").forEach((div, i) => {
    div.style.backgroundColor = bcgColor[i];
});
#rectangleWrapper div {
  height: 50px;
  margin: 4px;
}
<div id="rectangleWrapper">
<div id="rectangle-1">
</div>
<div id="rectangle-2">
</div>
</div>

Upvotes: 0

UraniumSteel
UraniumSteel

Reputation: 67

You're reinitializing j with each iteration of i, so if we walk your code:

i=0
j=0
recWrapDiv[0].style.background = bcgcolor[0]; 
now j=1
recWarpDiv[0].style.background = bcgcolor[1];
now i=1 and j will loop through 0 and 1 again
now j=0 again
recWrapDiv[1].style.background = bcgcolor[0]; 
now j=1
recWrapDiv[1].style.background = bcgcolor[1];
Finished
//All elements are set to bcgcolor[1].

I would change your for j loop to achieve what you want.

Upvotes: 1

wangdev87
wangdev87

Reputation: 8751

Just iterate array using for only once as children and bcgColor length are same.

const rectWrapDiv = document.getElementById("rectangleWrapper").children;
for (const prop of rectWrapDiv) {
  prop.classList.add("rectangle");
}

const bcgColor = ["red", "blue"];
for (let i = 0; i < rectWrapDiv.length; i++) {
    rectWrapDiv[i].style.background = bcgColor[i];
}
#rectangle-1, #rectangle-2 {
  height: 50px;
}
<div id="rectangleWrapper">

  <div id="rectangle-1">

  </div>
  <div id="rectangle-2">

  </div>
</div>

Upvotes: 1

Related Questions