You can’t just access DOM elements like properties in javascript.
To get DOM elements, the easiest way is to use the querySelector() or querySelectorAll() methods.
( See the documentation here: https://developer.mozilla.org/de/docs/Web/API/Document/querySelector )
In your case, you would get all td elements like this:
var x = document.querySelectorAll('table td');
which will return a NodeList containing all td‘s found. You can iterate over them like this:
x.forEach(function( td ){
var index = getRandomIntInclusive( 0, colors.length-1 ); // random int between 0 and 2
td.style.backgroundColor = colors[index];
});
Put all of this in your RandomColor function, to run it on click.
Also check out this random function taken from MDN ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random ), which gives you a random number within the given range:
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
I added the random function because yours returns a value between 0 and 10, but your colors array contains only 3 elements.
solved Coloring random color table of tr and td [duplicate]