In an array for a calculator, I have: x^y (in HTML it would be xy) Likewise I have x^-1 Or x-1. I can't figure out how to add it to the array for only those two buttons in the array so it displays xy and x-1 respectively instead of x < sup>y< /sup> (without the spaces, obviously) x < sup>-1< /sup>
js (missing the listeners, etc, but gives you the idea of what I'm aiming for):
const display = document.getElementById("display");
const buttonValues = [
"Rad", "º", "x!", "(", ")", "%", "AC",
"Inv", "sin", "log", "7", "8", "9", "÷",
"π", "cos", "ln", "4", "5", "6", "x",
"e", "tan", "√", "1", "2", "3", "+",
"Ans", "EXP", "^", "0", ".", "=", "-", "+/-", "x^-1",
]
const rightSymbols = [ "÷", "x", "-", "+", "="]
const topSymbols = ["(", ")", "%", "AC"]
const leftSymbols = ["Rad", "º", "x!", "Inv", "sin", "log", "π", "cos", "ln", "e", "tan", "√", "Ans", "EXP", "^", "+/-", "x^-1",]
//A+B, A×B, A-B, A÷B
let A = 0;
let operator = null;
let B = null;
function clearAll() {
A = null;
operator = null;
B = null;
}
for (let i = 0; i < buttonValues.length; i++) {
let value = buttonValues[i];
let button = document.createElement("button");
button.innerText = value;
//styling button colors
if (value == "=") {
button.style.backgroundColor = "brown";
}
else if (rightSymbols.includes(value)) {
button.style.backgroundColor = "orange";
}
else if (leftSymbols.includes(value)) {
button.style.backgroundColor = "darkorange";
button.style.color = "white";
}
else if (topSymbols.includes(value)) {
button.style.backgroundColor = "orange";
button.style.color = "white";
}
Answer
You can modify how the button's HTML is set using .innerHTML
for just those specific buttons.
Use .innerHTML
only when you want HTML formatting like superscript. For regular text, stick with .innerText
.
For eg. as per your implementation, you can do something like
if (value === "^") {
button.innerHTML = "x<sup>y</sup>";
} else if (value === "x^-1") {
button.innerHTML = "x<sup>-1</sup>";
} else {
button.innerText = value;
}
This way you can make sure "^" will render as xʸ
and "x^-1" will render as x⁻¹
making those buttons show superscripts properly.