Reputation: 176
I am making a table where when you press a button a random cell from the table changes its background color. I need to put variables with document.GetElementById
in an array but it doesn't seem to work. Here is my code below:
function setColor(){
var one = document.GetElementById('t1')
var two = document.GetElementById('t2')
var three= document.GetElementById('t3')
var cells = [];
cells.push("one");
cells.push("'two'");
cells.push("three");
var valueToUse = cells[Math.floor(Math.random() * cells.length)];
valueToUse.style.backgroundColor = "red";
}
Upvotes: 2
Views: 262
Reputation: 1001
Try:
function setColor(){
var one = document.getElementById('t1')
var two = document.getElementById('t2')
var three= document.getElementById('t3')
var cells = [];
cells.push(one.value);
cells.push(two.value);
cells.push(three.value);
var valueToUse = cells[Math.floor(Math.random() * cells.length)];
valueToUse.style.backgroundColor = "red";
}
You need to push the value to each element instead of a string with the name of it
Upvotes: 0
Reputation: 190905
You are pushing strings into cells
, not the elements.
function setColor(){
var one = document.getElementById('t1')
var two = document.getElementById('t2')
var three= document.getElementById('t3')
var cells = [];
cells.push(one);
cells.push(two);
cells.push(three);
var valueToUse = cells[Math.floor(Math.random() * cells.length)];
valueToUse.style.backgroundColor = "red";
}
Also as j08691 says, its getElementById
, not GetElementById
.
Upvotes: 1
Reputation: 386560
You could omit the array and use the random number directly to address the element.
BTW, getElementById
starts with a small letter.
function setColor() {
var randomNumber = Math.floor(Math.random() * 3) + 1,
element = document.getElementById('t' + randomNumber);
element.style.backgroundColor = "red";
}
Upvotes: 0
Reputation: 2433
You are adding strings in your cells
array. Use the following:
cells.push(one);
cells.push(two);
cells.push(three);
Upvotes: 1
Reputation: 1432
You are pushing strings into the cells array, these are completely different objects from the document elements themselves.
cells.push(one);
cells.push(two);
cells.push(three);
is what you want.
Upvotes: 1