I want to change the text color of a button when I click on it using a function.
so I made a function for it which does not work.
code:
function correct(x) {
document.getElementById("x").style.color = "green";
}
function wrong(y) {
document.getElementById("y").style.color = "red";
}
function answer() {
if (document.getElementById("p").innerHTML == "question 1") {
correct(bt1);
wrong(bt2);
} else if (document.getElementById("p").innerHTML == "question 2") {
correct(bt2);
wrong(bt1);
}
}
<p id="p">question 1</p>
<button id="bt1" onclick="answer()"> option 1</button>
<button id="bt2" onclick="answer()"> option 2</button>
>Solution :
You don’t need to call getElementById() to get the buttons to change. answer() passes the buttons directly, use the parameters.
function correct(x) {
x.style.color = "green";
}
function wrong(y) {
y.style.color = "red";
}
function answer() {
if (document.getElementById("p").innerHTML == "question 1") {
correct(bt1);
wrong(bt2);
} else if (document.getElementById("p").innerHTML == "question 2") {
correct(bt2);
wrong(bt1);
}
}
<p id="p">question 1</p>
<button id="bt1" onclick="answer()"> option 1</button>
<button id="bt2" onclick="answer()"> option 2</button>
Note that use bt1 and bt2 as arguments takes advantage of the fact that element IDs automatically become global variables. This is not generally considered good style.