Reputation: 463
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
Reputation: 206111
textContent
Element.innerHTML = "bla"
to set a new inner HTML)Element.textContent = "bla"
to set a new text contentonclick
- it's discouraged for code maintainability reasons<button>
for semantic reasons and accessibilityHere'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
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
Reputation: 28750
It's not a reference, you'll have to set it directly at the end:
document.getElementById('elementTEST').innerHTML = buttonValue
Upvotes: 3