0

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!

5
  • 2
    Side note, it's getElementById not getElementsById. jsfiddle.net/j08691/h6es01ur. IDs are unique unlike classes. Commented Jan 26, 2017 at 15:06
  • 2
    Welcome to Stack Overflow Wes Asbell! Have you checked your console? You'll see what's causing the problem there. Commented Jan 26, 2017 at 15:07
  • 2
    @j08691 That's not a side note, it's the problem. That and the [0]. Commented Jan 26, 2017 at 15:07
  • 3
    Two issues: Change getElementsById to getElementById, and remove the [0]. Using getElementById will 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: Commented Jan 26, 2017 at 15:08
  • check the working Fiddle. jsfiddle.net/Pp5up/22 Commented Jan 26, 2017 at 15:10

1 Answer 1

2

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.

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.