skip to Main Content

Javascript

const btn0 = document.querySelector('.btn0');
btn0.addEventListener('click', function() {
    showNum(0);
})

function showNum(value)

HTML

<input type="button" value="0" name="btn0" id="btn0"  />

I have included the relevant code above. The showNum function is fully implemented and working, I just didn’t include it because it was irrelevant.

I need to call the showNum function with an event listener but can’t figure out why my code is not working. When debugging I can see that addBtn is null and no matter what I try it stays that way. I have been struggling with this for an hour and am frustrated at how simple it should be.

I have tried different ways of initializing addBtn such as using getElementByName, but when debugging through the program btn0 is always null.

2

Answers


  1. btn0 is not a class instead it is an id so you have to use # in place of . in

    const btn0= document.querySelector('#btn0');
    
    const btn0 = document.querySelector('#btn0');   // CHANGE
    btn0.addEventListener('click', function() {
      showNum(0);
    })
    
    function showNum(value) {
      console.log('Inside showNum functon with value: ', value);
    }
    <input type="button" value="0" name="btn0" id="btn0" />

    You can also find button using attribute also as:

    document.querySelector('[name="btn0"]');
    
    const btn0 = document.querySelector('[name="btn0"]'); // CHANGE
    btn0.addEventListener('click', function() {
      showNum(0);
    })
    
    function showNum(value) {
      console.log('Inside showNum functon with value: ', value);
    }
    <input type="button" value="0" name="btn0" id="btn0" />
    Login or Signup to reply.
  2. You a are using querySelector to select the button element with the class name .btn0 However, in the HTML , the button element has an ID of btn0, not a class name.

    To select an element by ID, you should use the getElementById method instead of querySelector. Try changing your code to the following:

    const btn0 = document.getElementById('btn0');
    btn0.addEventListener('click', function() {
        showNum(0);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search