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)asked Nov 16, 2014 at 10:07 33 1 1 gold badge 1 1 silver badge 4 4 bronze badges 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
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
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 >);