skip to Main Content

I’m a beginner in JS, just got the template of a calculator in HTML and I’m trying to build its functionalities through JS. I’m starting with the addition button initially.

I wrote the code below, however, I keep getting this error on the browser console: Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) at script.js.9:9

Could anyone please advise?


const a = Number(document.getElementById('num1'));
const b = Number(document.getElementById('num2'));

const btnSoma = document.querySelector('.add');

//sum
btnSoma.addEventListener('click', function() {
  const soma = a + b;
  console.log(soma);
});

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculadora Simples</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="calculator">
        <input type="number" id="num1" placeholder="Número 1">
        <input type="number" id="num2" placeholder="Número 2">
        <div class="buttons">
            <button onclick="add()">+</button>
            <button onclick="subtract()">-</button>
            <button onclick="multiply()">*</button>
            <button onclick="divide()">/</button>
        </div>
        <p id="result">Resultado: </p>
    </div>
    <script src="script.js"></script>
</body>
</html>

3

Answers


  1. Chosen as BEST ANSWER

    I believe I found an answer, at least here it's working perfectly: to access a onclick button from HTML in a JavaScript file, one can simply use function and name it the same as the onclick. In the thread example, function add() {}


  2. This is likely because the script is executed before the HTML has finished loading. To solve this issue, you should ensure that your script runs after the DOM has loaded.

    One way to do this is by placing your script at the end of the body tag, just before the closing tag, or by wrapping your code in an event listener for the DOMContentLoaded event.

    document.addEventListener("DOMContentLoaded", function() {
                const btnSoma = document.querySelector('.add');
    
                btnSoma.addEventListener('click', function() {
                    const a = Number(document.getElementById('num1').value);
                    const b = Number(document.getElementById('num2').value);
                    const soma = a + b;
                    console.log(soma);
                });
            });
    
    Login or Signup to reply.
  3. You are trying to select an element with the class .add, which doesnt exist.

    Instead of using onClick on each button do this: class="add" – for the add Button. Now do the same for the other buttons with substract, …

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search