The issue is that your DOM is not yet loaded when you are trying to access the buttons. Wrap your onclick handlers in window.load and everything should work fine:
window.onload = function () {
var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a') {
myButton[0].style.backgroundColor = "green";
} else {
myButton[0].style.backgroundColor = "red";
}
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b') {
myButton[1].style.backgroundColor = "green";
} else {
myButton[1].style.backgroundColor = "red";
}
}
}
I am actually surprised this works under Webkit and Mozilla. I have created a small demo fiddle. In all cases, in all browsers the object comes out as null before load, unless the script block is after the element you are accessing inside the body.
Notice though that there is a difference in how getElementsByTagName reacts inside different browsers, it is different than getElementById: fiddle
Another alternative would be to not wait for window.onload would be to wait for document.body because window.onload happens after all content including images is loaded.
function Start() {
if (document.body) {
var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a') {
myButton[0].style.backgroundColor = "green";
} else {
myButton[0].style.backgroundColor = "red";
}
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b') {
myButton[1].style.backgroundColor = "green";
} else {
myButton[1].style.backgroundColor = "red";
}
}
}
}
setInterval(Start, 50); // 50 ms is a small enough interval to retry
;... really not a good idea(and a few other corner cases, and you're good to go.;to the end of every assignments and function calls, even for inline functions, because they always make the code much clearer, prevents some errors and follow my habit writing most "C-style" languages