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
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: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.
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 :
Thank You