Background color using array and object for reversible repeatable div

var ar = ["one_in", "two_in", "three_in"];
    var colors = {};
    [ar[0]] = 'blue';
    [ar[1]] = 'green';
    [ar[2]] = 'red';
x = document.getElementsByTagName('DIV');
for (var i = 0 ; i < x.length ; i++ ){
    x[i].style.backgroundColor = colors[x[i].className];
}
.one_in,.two_in{
width:100px;
height:100px;
border:1px solid #000;
}
<div class="one_in"></div><div class="two_in"></div>
Run codeHide result

why not continue this work, I want the div to be colored with the appropriate colors and div class, as mentioned in the array and the object, I know this is a simple question for you, there may be a small mistake

https://jsfiddle.net/qothk6g3/3/

+4
source share
1 answer

You are missing colorin front of a property with an array element as an accessor property .

var ar = ["one_in", "two_in", "three_in"],
    x = document.getElementsByTagName('DIV'),
    i,
    colors = {};

colors[ar[0]] = 'blue';
colors[ar[1]] = 'green';
colors[ar[2]] = 'red';

for (i = 0 ; i < x.length ; i++) {
    x[i].style.backgroundColor = colors[x[i].className];
}
.one_in,.two_in { width:100px; height:100px; border:1px solid #000; }
<div class="one_in"></div><div class="two_in"></div>
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1664852/


All Articles