<button class="js-button" onclick="
let buttonElement = document.querySelector('.js-button').innerHTML;
if (buttonElement === 'Subscribe') {
buttonElement = 'Subscribed';
} else {
buttonElement = 'Subscribe';
}
">Subscribe</button>
When we click on the button, it should change to ‘Subscribed’ from ‘Subscribe’ and vice versa.
When I am saving .innerHTML
along with the button in the variable buttonElement
, the If statement doesn’t work properly. But, when I use the .innerHTML
inside the If statement (ex. if (buttonElement.innerHTML === ‘Subscribe’) and I am not saving innerHTML inside the variable, the If Statement starts working properly. Can you please let me know what could be the reason.
2
Answers
You can. And indeed you are. The code just isn’t doing anything that you are observing. For example, replace those assignment statements with an
alert()
and you can observe that it works:Perhaps you meant to do something other than assign a value to a variable? For example, if you wanted to set the
innerHTML
of the element, you can do that:As an aside, you’ll find that stuffing a lot of JavaScript code into an
onclick
attribute gets messy fast. Instead, attach it as a click handler:buttonElement
is a string and is unlinked from theinnerHTML
so when you change the string then nothing happens. In fact you don’t need that variable inside the online function.See example.