-2

I tried to learn some basic of different about JS and TS but when I code basic HTML and JS for plus 2 number (first of all I didn't expect it can add for Ex. 10 + 2 = 12 I just expect 102). But when I opened my html file for test my script console thrown this error

Uncaught TypeError: Cannot read property 'addEventListener' of null

So, I can't press add button too here my HTML code

const button = document.querySelector("button1");
const input1 = document.getElementById("input1");
const input2 = document.getElementById("input2");

function add(num1, num2) {
    if ( typeof num1 === "number" && typeof num2 === "number") {
        return num1 + num2;

    } else {
        return +num1 + +num2;
    }
}

button.addEventListener("click", function() {
    console.log(add(input1.value, input2.value));
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Understanding Typescript</title>
    <script src="js-only.js" defer></script>
</head>
<body>
    <input type="number" id="num1" placeholder="number1">
    <input type="number" id="num2" placeholder="number2">
    <button>Add!</button>
</body>
</html>

Can you tell me what are my mistakes?

artaro
  • 1
  • 1
  • 1
    There is no `button1` in your HTML code. – jabaa May 18 '21 at 21:51
  • `input1` => `num1`, `input2 => num2`, `button1` => `button`. The selectors have to match. See [this answer](https://stackoverflow.com/a/56074659/6243352) for a canonical resource you can find through a web search. – ggorlen May 18 '21 at 21:51
  • You have no `` element in your code, so `querySelector` can't find it. – Heretic Monkey May 18 '21 at 21:55
  • @ggorlen I tried this it works thx a lot. But I expected that 2 number do string combining for next use of TypeScript resolve this. – artaro May 18 '21 at 22:54

1 Answers1

1

querySelector takes a CSS-style element query, so it's looking for a <button1> tag, which doesn't exist, so it's setting button to null. You either need to query for "button" (which is likely to break if you add a second button to your page), or (better) give your button an ID like you have for the <input> elements:

<button id="addButton">Add!</button>
const button = document.getElementById("addButton");
Harry Cutts
  • 1,195
  • 10
  • 21