AmericanMade
AmericanMade

Reputation: 463

Change text on button when clicked with JavaScript

I'm trying to change the text of a button when it's pressed with JavaScript. Should be very straightforward, however, it's not working. Can anyone explain? Here's my code:

function changeInnerHTML() {
  var buttonValue = document.getElementById('elementTEST').innerHTML;
  var buttonValueInnerHTMLBegin = '<p id="elementTEST">';
  var buttonValueInnerHTMLEnd = '</p>';
  alert("buttonValue = " + typeof(buttonValue)); // -> "string"
  if (buttonValue == "Online") {
    alert("turn off"); // -> "turn off"
    buttonValue = buttonValueInnerHTMLBegin + "Offline" + buttonValueInnerHTMLEnd; // -> DOESN'T CHANGE ANYTHING
    alert("turned off"); // -> "turned off"
  } else if (buttonValue == "Offline") {
    buttonValue = "Online";
  } else {
    alert("There's a problem");
  }
}
<div class="containerTEST">
  <div class="divTEST" onclick="changeInnerHTML()">
    <p id="elementTEST">Online</p>
  </div>
</div>

I have run this both with and without the "buttonValueInnerHTMLBegin/End" variables being included, and I get the same result.

I get the alerts (shown as comments in the code), but the text/innerHTML doesn't change.

Thanks for any help!

Upvotes: 0

Views: 69

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206111

  • There's absolutely no reason to change the HTML. Change only the textContent
  • (Use Element.innerHTML = "bla" to set a new inner HTML)
  • Use Element.textContent = "bla" to set a new text content
  • Don't use inline JS onclick - it's discouraged for code maintainability reasons
  • Use a <button> for semantic reasons and accessibility

Here's a simpler version

[...document.querySelectorAll(".toggleOnline")].forEach( el => 
  el.addEventListener("click", () => {
     el.textContent = /online/i.test(el.textContent) ? "Offline" : "Online";
  })
);
.toggleOnline {
  border: none;
  border-radius: 0;
  background: #ddd;
  padding: 8px 16px;
}
<button class="toggleOnline" type="button" aria-live="assertive" aria-atomic="true">
  Online
</button>

Now you can also tab your element and use Spacebar or Enter to toggle your button.

Upvotes: 1

Aymen
Aymen

Reputation: 1496

try this:

 var buttonValue = document.getElementById('elementTEST');  
    function changeInnerHTML(){
        if (buttonValue.innerHTML == "Online")
            buttonValue.innerHTML= "Offline";                  
        else if (buttonValue.innerHTML == "Offline") 
            buttonValue.innerHTML = "Online";
    }

codepen: example

Upvotes: 1

Mathew Berg
Mathew Berg

Reputation: 28750

It's not a reference, you'll have to set it directly at the end:

document.getElementById('elementTEST').innerHTML = buttonValue

Upvotes: 3

Related Questions