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
btn0
is not aclass
instead it is anid
so you have to use#
in place of.
inYou can also find button using attribute also as:
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: