skip to Main Content
<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


  1. 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:

    <button class="js-button" onclick="
        let buttonElement = document.querySelector('.js-button').innerHTML;
    
        if (buttonElement === 'Subscribe') {
          alert('Subscribed');
        } else {
          alert('Subscribe');
        }
      ">Subscribe</button>

    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:

    <button class="js-button" onclick="
        let buttonElement = document.querySelector('.js-button');
    
        if (buttonElement.innerHTML === 'Subscribe') {
          buttonElement.innerHTML = 'Subscribed';
        } else {
          buttonElement.innerHTML = 'Subscribe';
        }
      ">Subscribe</button>

    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:

    let buttonElement = document.querySelector('.js-button');
    
    document.querySelector('.js-button').addEventListener('click', function () {
      if (buttonElement.innerHTML === 'Subscribe') {
        buttonElement.innerHTML = 'Subscribed';
      } else {
        buttonElement.innerHTML = 'Subscribe';
      }
    });
    <button class="js-button">Subscribe</button>
    Login or Signup to reply.
  2. buttonElement is a string and is unlinked from the innerHTML so when you change the string then nothing happens. In fact you don’t need that variable inside the online function.
    See example.

    <button class="js-button" 
    onclick="
        if (this.innerHTML === 'Subscribe') {
          this.innerHTML = 'Subscribed';
        } else {
          this.innerHTML = 'Subscribe';
        }
      ">Subscribe</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search