I'm trying to make a button that switches the text in a <p> element. This is the HTML code:
<button onclick="toggle()">Switch</button>
<p id="unit">metric</p>
And this is the javaScript:
function toggle() {
if(document.getElementById("unit").text()=="metric"){
document.getElementById("unit").innerHTML="imperial";}
else if(document.getElementById("unit").value=="imperial"){
document.getElementById("unit").value="metric";}
}
};
What am I doing wrong?
Always use .textContent or .innerHTML unless you're dealing with an input or textarea element:
function toggle() {
const unit = document.getElementById("unit")
if (unit.textContent === "metric") {
unit.textContent = "imperial";
} else if (unit.textContent === "imperial") {
unit.textContent = "metric";
}
}
<button onclick="toggle()">Switch</button>
<p id="unit">metric</p>
Only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With