Is there a shorter way to do this in Javascript? (more below)

Viewed 37

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>
1 Answers

Check the class instead of the ID.

Since you aren't deliberately inserting or retrieving HTML markup, you should also use textContent instead of innerHTML, it's safer, quicker, and more semantically appropriate.

document.addEventListener('click', e =>{
    if (e.target.matches('.numBtn')){
        const x = document.createElement('p');
        x.textContent = e.target.textContent;
        screen.appendChild(x)
    }
})

You can also use insertAdjacentHTML, though this has the same problems as innerHTML.

document.addEventListener('click', e =>{
    if (e.target.matches('.numBtn')){
        screen.insertAdjacentHTML(
            'beforeend',
            `<p>${e.target.textContent}</p>`
        );
    }
})
Related