Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a toggle for switching text?

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?

like image 492
Thor Abegg Avatar asked Mar 12 '26 06:03

Thor Abegg


1 Answers

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.

like image 142
CertainPerformance Avatar answered Mar 13 '26 20:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!