Reputation:
I'm about to make a random background color javascript code. So when you refresh the page, all element's background color will change, but in Chrome, I got an error :
"Uncaught TypeError: Cannot set property 'background' of undefined"
Here's my JavaScript and HTML :
var colors = [
[
[65], [131], [215]
], [
[217], [30], [24]
], [
[245], [215], [110]
], [
[135], [211], [124]
]
];
//Getting a random color
var random = Math.floor(Math.random() * 4);
var block = document.getElementsByClassName('block');
var obj;
for (obj in block) {
if (block.hasOwnProperty(obj)) {
block[obj].style.background =
"rgb" + "(" + colors[random][0] + ", " + colors[random][1] + ", " + colors[random][2] + ")";
}
}
document.getElementById('body').style.background = "rgb" + "(" + colors[random].r + ", " + colors[random].g + ", " + colors[random].b + ")";
<a href="#">
<li class="block block1">
<i class="icon-vcard"></i>
<h3>Contact us</h3>
<content>
<h3>Contact us</h3>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
</content>
</li>
</a>
<a href="#">
<li class="block block2">
<i class="icon-users"></i>
<h3>Staff</h3>
<content>
<h3>Staff</h3>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
</content>
</li>
</a>
<a href="#">
<li class="block block3">
<i class="icon-wrench"></i>
<h3>Tools</h3>
<content>
<h3>Tools</h3>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
</content>
</li>
</a>
<a href="#">
<li class="block block4">
<i class="icon-info"></i>
<h3>About us</h3>
<content>
<h3>About us</h3>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</p>
</content>
</li>
</a>
</ul>
Upvotes: 1
Views: 5151
Reputation: 5781
You are iterating over the blocks with a for...in, which also causes you to iterate over the "length" property.
A better approach:
var blocks = document.getElementsByClassName('block');
for (var i=0;i<blocks.length;i++) {
blocks[i].style.background =
"rgb" + "(" + colors[random][0] + ", " + colors[random][1] + ", " + colors[random][2] + ")";
}
Upvotes: 2