document.querySelector is returning null for a very simple beginner problem. I have no idea why

37 views Asked by At

html is basically boiler plate

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="script.js"></script>
  </head>
  <body>
    <input id="text-input" required placeholder="Please input a value" />
    <button id="check-btn"></button>
    <div id="result"></div>
  </body>
</html>

js

const textInput = document.querySelector("input");

console.log(textInput);

returns null. Ive watched youtube videos and do exactly what they did and console will log the input element. Ive also tried using .text-input and #text-input

2

There are 2 answers

3
Abdullah On

First of all, try to use script tag after body tag ( you're using it in head tag ). Now lets come to solution so you're using wrong command. Try this javascript code instead:

const textInput = document.querySelector("text-input").innerHTML; console.log(textInput);

I hope this answer will solve your problem.

0
I_am_prince On

As per your code, your script runs before the complete DOM renders. so that your queryselector didn't able to get input element.

To Resolve It Just add defer in your script tag.

It will executed after the page has finished parsing.

Solution code :

const textInput = document.querySelector("input");

console.log(textInput);
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="script.js" defer></script>
  </head>
  <body>
    <input id="text-input" required placeholder="Please input a value" />
    <button id="check-btn"></button>
    <div id="result"></div>
  </body>

Thank You