views:

42

answers:

3

So for some reason this unobtrusive javascript code is not working and I can't figure out for the life of me why it won't work.

I dynamically change the className of a div element and therefore I expect the CSS to reflect that change. However it doesn't. Here's the simplified code.

html:

<head>
    <title>Your Page</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script type="text/javascript" src="us.js"></script>
</head>

<body>
  <div id="wrapper">    
    <h1 id="title">Your Page</h1>   
  </div>
</body>

javascript:

window.onload = function() {
  document.getElementById("wrapper").className = "2";
}

css:

#wrapper{
    background-color: white;
}

#wrapper.1 {
    background-color: black;
}

#wrapper.2 {
    background-color: red;
}

#wrapper.3 {
    background-color: blue;
}

I look at the wrapper div in firebug and it shows the class being changed to "2". However, the webpage doesn't reflect that by changing the background color to be red. (it doesn't work with changing text color either. I tried that.). I know the CSS is correctly loading. So what is the problem?

+1  A: 

Did you try using a different class name? Check http://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-names . css class names cannot start with numbers.

z33m
+4  A: 

Your css class names need to begin with a letter, like this:

#wrapper.num1 {
    background-color: black;
}

#wrapper.num2 {
    background-color: red;
}

#wrapper.num3 {
    background-color: blue;
}
Nick Craver
+1  A: 

2 is an invalid class name. Your class name cannot be a number; it must be an alphanumeric string starting with a letter.

meagar