I m getting uncaught typeError forEach is getting null values in my calculator so nothing is coming ion calci screen ..
(function(){
let screen= document.querySelector(".screen");
let buttons= document.querySelector(".btn");
let clear= document.querySelector(".btn-clear");
let green= document.querySelector(".btn-green");
buttons.forEach(function(btn) {
button.addEventListener('click', function(e){
let value = e.target.dataset.num;
screen.value = value;
})
});
})();
CodePudding user response:
document.querySelector
returns null
if there is no matched element. If you're iterate over found elements, use this snippet:
let buttons = [...document.querySelectorAll(".btn")];
This snippet uses spread syntax, which converts querySelectorAll
value to an array.
CodePudding user response:
document.querySelector can return null
if no matches found with your selector. That's why forEach is failing, since it is becoming null.forEach()
.
You can check if (Array.isArray(buttons))
and then loop it.