我想更改 ID 为 .html 的 HTML 元素的背景颜色foo
。我目前有这段代码:
var hexcode = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
// this chooses a random value from the array hexcode
var ranval = function() {
return hexcode[Math.floor(Math.random()*hexcode.length)];
}
// six ranval() are put together to get color
var colorname = "#" + ranval() + ranval() + ranval() + ranval() + ranval() + ranval();
// trying to put the value on the background of element with "foo" ID.
document.getElementById("foo").style.color = colorname;
此代码引发此错误:
Uncaught TypeError: Cannot read property 'style' of null
我确定该 IDfoo
存在。