0
const loginInput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");

function onLoginBtnClick() {
    const value = loginInput.value;
    if (value === "") {
        alert("Please write your name.");
    }
}

loginButton.addEventListener("click", onLoginBtnClick);

It's JS code.

I keep getting "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')" error. I'm trying to make a site that displays the username in the console window when I enter the username and click the login button.

I tried to change the code in line 1~2 as below.

const loginForm = document.getElementById("#login-form");
const loginInput = loginForm.querySelector("input");
const loginButton = loginForm.querySelector("button");
  • Make sure your code is executing at the right point of time, meaning it needs to execute after those elements exist in the DOM otherwise they will not be found. – Patrick Evans Jan 03 '23 at 22:48
  • If you are getting elements by id, you only need to indicate the name of the id (without the `#`) – blurfus Jan 03 '23 at 22:50

1 Answers1

0

When you do document.getElementById("#login-form"); it's not going to work - when you do getElementById you don't prefix the id with a #, whereas with with .querySelector you do (to indicate that it is the ID)

dave
  • 62,300
  • 5
  • 72
  • 93
  • OP is probably running the script too early. He did not make this mistake in the first snippet, and he said that it didn't work. – Spectric Jan 03 '23 at 22:50