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!
getElementByIdnotgetElementsById. jsfiddle.net/j08691/h6es01ur. IDs are unique unlike classes.[0].getElementsByIdtogetElementById, and remove the[0]. UsinggetElementByIdwill only return one element, and so you don't need to specify an index. Working example: jsfiddle.net/Pp5up/12 EDIT: Seems j08691 and Mike C have beat me to the punch! c: