I'm making a calculator, and I'm adding eventListeners to the number buttons.
JS looks like this:
document.addEventListener('click', e =>{
if (e.target.matches('#num1')){
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
}
else if (e.target.matches('#num2')){
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
}
else if (e.target.matches('#num3')){
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
}
})
It's working alright, but there are 10 number buttons obviously, so I tried to make it shorter with tenary operators, or make a function out of this part:
const x = document.createElement('p');
x.innerHTML = e.target.innerHTML;
screen.appendChild(x)
However, this way e.target is undefined. Any suggestions appreciated!
Markup:
<button type='button' class='btn numBtn' id='num1'>1</button>
<button type='button' class='btn numBtn' id='num2'>2</button>
<button type='button' class='btn numBtn' id='num3'>3</button>