最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'className' of null - Stack Overflow

programmeradmin1浏览0评论

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;
}

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;
}
Share Improve this question asked Nov 16, 2014 at 10:07 rbazzlerbazzle 331 gold badge1 silver badge4 bronze badges 2
  • Is the script executed before the document has loaded? – Ja͢ck Commented Nov 16, 2014 at 10:09
  • Are you running this before the DOM is loaded? – Scimonster Commented Nov 16, 2014 at 10:09
Add a ment  | 

2 Answers 2

Reset to default 9

I'd say this es 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
});

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

发布评论

评论列表(0)

  1. 暂无评论