skip to Main Content

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

3

Answers


  1. Your code is running before the DOM is fully loaded. You can try either placing the script at the bottom the body tag OR wrapping your code with DOMContentLoaded event:

    document.addEventListener("DOMContentLoaded", (event) => {
      //add your code
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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

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