I want to change the background color of an HTML element whose ID is foo. I have this code at present:
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;
This code is throwing this error:
Uncaught TypeError: Cannot read property 'style' of null
I'm sure that ID foo exists.
asked Jan 7, 2013 at 2:20
Santosh Kumar
28.3k21 gold badges72 silver badges126 bronze badges
2 Answers 2
Your error occurs because you're trying to access your element before the DOM is ready. Wait for the window to load before accessing it:
// Credit: http://paulirish.com/2009/random-hex-color-code-snippets/
function random_color() {
return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
}
window.onload = function() {
document.getElementById("foo").style.backgroundColor = random_color();
};
answered Jan 7, 2013 at 2:26
Blender
300k55 gold badges463 silver badges513 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
Gabriel Gartz
Your script will have errors @Blender, because if you get a number less then 6 characters the color wont change or changes wrong.
Blender
@SantoshKumar: Sorry,
load should be onload.Gabriel Gartz
@Blender still with the same problem, will not aways have 6 characters. You can complete it using RegExp, or use another like solution like what I did.
Santosh Kumar
What if I want to change background color of body?
Gabriel Gartz
@SantoshKumar Use
document.body.style.backgroundColor = random_color() on the onload callback |
The simple way to fix your code is:
var random_color = function() {
function randomHex() {
return Math.floor(Math.random() * 15).toString(16);
}
var str = '#';
for(var i = 6; i--;) {
str += randomHex();
}
return str;
}
window.onload = function() {
// For your body background color
document.body.style.backgroundColor = random_color();
// For your foo element TEXT color
document.getElementById("foo").style.color = random_color();
// For your foo element BACKGROUND color
document.getElementById("foo").style.backgroundColor = random_color();
};
answered Jan 7, 2013 at 2:38
Gabriel Gartz
2,87024 silver badges24 bronze badges
Comments
lang-js
<script>tag (before or after the body)?style.backgroundColorinstead ofstyle.color.