Search code examples
javascripteventsinnerhtml

element.innerHTML is not giving expected result in Javascipt


I'm not sure if my title for this question makes sense (Please suggest if it doesn't);

so i have this very simple examlpe.. in the HTML:

 <button class="btn" type="button"> button1 </button>
 <button class="btn" type="button"> button2 </button>

And in JS:

window.onload = () => {
  var buttons = document.querySelectorAll('.btn');

  buttons.forEach((btn) => {
    btn.addEventListener('click', () => {
      if (btn.innerHTML === 'button1') {
        btn.style.background = 'green';
        console.log('Button1 is clicked');
      } else {
        btn.style.background = 'red';
        console.log('Button2 is clicked');
      }
    });
  });
}

I thought it will behave like expected; but any button i click its background turns red.

Can you please explain why is this happening?

Thanks a lot in advance.


Solution

  • Condition btn.innerHTML === '1' is always false as the content of first button's innerHTML is button1 and second button's innerHTML is button1.

    You could try

    if (btn.innerHTML.endsWith('1')){...
    

    Update: There are some spaces around the text content. You should trim the value to remove the spaces. Also, I will suggest you to use innerText or textContent instead of innerHTML if the content is only string (no HTML):

    window.onload = () => {
      var buttons = document.querySelectorAll('.btn');
    
      buttons.forEach((btn) => {
        btn.addEventListener('click', () => {
          if (btn.textContent.trim() === 'button1') {
            btn.style.background = 'green';
            console.log('Button1 is clicked');
          } else {
            btn.style.background = 'red';
            console.log('Button2 is clicked');
          }
        });
      });
    }
    <button class="btn" type="button"> button1 </button>
    <button class="btn" type="button"> button2 </button>