You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端新手求助:document.querySelector返回null的问题

解决document.querySelector返回null的问题

你的问题根源在于脚本执行时机不对:浏览器从上到下解析HTML,你把<script>标签放在了<head>里,此时<body>中的input元素还没被渲染到DOM树中,document.querySelector自然找不到目标元素,返回null。

给你三种可行的解决办法:

1. 移动脚本位置到body末尾

把<script>标签放在所有DOM元素之后,确保执行JS时目标元素已经存在:

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

2. 监听DOM加载完成事件

在JS中通过DOMContentLoaded事件,等待整个DOM树构建完成后再执行查询操作:

document.addEventListener('DOMContentLoaded', () => {
  const textInput = document.querySelector("#text-input");
  console.log(textInput);
});

3. 给script标签添加defer属性

defer属性会让浏览器在解析完DOM后再执行脚本,同时不阻塞HTML解析:

<head>
  <!-- 其他标签不变 -->
  <script src="script.js" defer></script>
</head>

你看到视频里别人的代码能正常运行,大概率是他们用了上述某一种延迟执行的方式,只是没特意说明。

内容的提问来源于stack exchange,提问作者user34539

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 23:53:25