Reputation: 283
I am trying to do something very similar to the JSFiddle found here, http://jsfiddle.net/Pp5up/ , where every time a page loads the background color changes.
The issue I am running into is that the example above changes the body's background. I am trying to change the background color of a div every time a page loads. I have tried for hours, but just can't seem to get it to work properly. Here is my code: http://jsfiddle.net/Pp5up/11/
HTML
<div id="nm-single-product-bg">
Test
</div>
CSS
#nm-single-product-bg.style1 {background:red;}
#nm-single-product-bg.style2 {background:blue;}
#nm-single-product-bg.style3 {background:black;}
JS
var rand = Math.floor((Math.random()*3)+1);
var style = "style" + rand;
document.getElementsById("nm-single-product-bg")[0].className+=style
If anyone can help, I would be so appreciative!
Upvotes: 0
Views: 204
Reputation: 4199
Change this line
document.getElementsById("nm-single-product-bg")[0].className+=style
to this
document.getElementById("nm-single-product-bg").className+=style
The cause for this is already mentioned in comments :)
ID is unique for each element, so its getElementById
instead of getElementByIds
& since it always returns one unique div, no need for that array subscript.
Upvotes: 2