3

This isn't working. I have an element in my html with the id "color". What is the deal? I just want it to add to the class of that element.

var el = document.getElementById("color");
var number = Math.floor((Math.random() * 5) + 1);

switch (number) {
    case 1:
        el.className += " blue";
        break;

    case 2:
        el.className += " yellow";
        break;

    case 3:
        el.className += " red";
        break;

    case 4:
        el.className += " green";
        break;

    case 5:
        el.className += " purple";
        break;
}
2
  • Is the script executed before the document has loaded? Commented Nov 16, 2014 at 10:09
  • Are you running this before the DOM is loaded? Commented Nov 16, 2014 at 10:09

2 Answers 2

9

I'd say this comes from the fact the body is not loaded when you try to get the #color element.

Just wrap the thing inside this

window.onload = function () {
    // your code
};

Or you can load your code at the end of the body

<body>
    <!-- you content -->
    <script src="your-script.js"></script>
</body>

And finally you can listen for the DOMContentLoaded event. It's a little faster than window.onload but has slightly less support, IE9+.

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code
});
Sign up to request clarification or add additional context in comments.

5 Comments

@Jonathan Good suggestion, though I could have updated my answer had you commented :p
On a page with a lot of images, hooking into DOMContentLoaded event is actually a lot faster than onLoad.
Or by convention include your js at the end, before </body>
@argentum47 This is what is already stated in my answer, actually
my mistake. didn't see that.
0

I declared a variable "el" that wasn't within the scope of the switch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.