首页 > 解决方案 > getElementByID 返回 Null 的 Dom 元素。网页包

问题描述

我试图在我的 DOM 中抓取一个元素,getElementByID但我一直在开发控制台中收到一条错误消息,说Cannot read property 'addEventListener' of null.

我正在使用 webpack 来捆绑我的代码。我最初认为这是因为 webpack 在我的 html 的头部注入了 script 标签,但后来通过让 webpack 在我的 html 正文的末尾注入它来解决这个问题。这样做我仍然有问题再次发生。

我已经重新创建了我期望在 codepen 中发生的事情,即当单击我页面上的汉堡包时,将显示一个导航列表。基本上,我只是做了一个红框和一个蓝框,当点击红框时,蓝框要么出现,要么消失。它也以我想要的方式工作,所以我知道这与我的 webpack 设置有关。

这是我的代码。

html

<header>
    <div class="header__container">
      <nav class="nav">
        <div class="nav_items_left">
          <svg class="blogr__logo"></svg>
        </div>
        <div class="nav_items_right">
          <svg class="hamburger__img" id="hambuger"></svg>
          <div class="nav__bar" id="nav_bar">
            <div class="nav__item" id="nav_item">
              <p class="nav_head_title">Product<i class="fas fa-chevron-down"></i></p>
              <div class="sub_item" id="sub_item">
                <a href="#">Overview</a>
                <a href="#">Pricing</a>
                <a href="#">Marketplace</a>
                <a href="#">Features</a>
                <a href="#">Integrations</a>
              </div>
            </div>
            <div class="nav__item" id="nav_item">
              <p class="nav_head_title">Company<i class="fas fa-chevron-down"></i></p>
              <div class="sub_item" id="sub_item">
                <a href="#">About</a>
                <a href="#">Team</a>
                <a href="#">Blog</a>
                <a href="#">Careers</a>
              </div>
            </div>
            <div class="nav__item" id="nav_item">
              <p class="nav_head_title">Connect<i class="fas fa-chevron-down"></i></p>
              <div class="sub_item" id="sub_item">
                <a href="#">Contact</a>
                <a href="#">Newsletter</a>
                <a href="#">LinkedIn</a>
              </div>
            </div>
            <hr class="line__break">
            <div class="mobile_buttons">
              <a href="" class="mobile_login">Login</a>
              <a href="" class="mobile_sign_up">Sign Up</a>
            </div>
          </div>
        </div>
      </nav>

      <div class="hero__section">
        <div class="headers">
          <h1>A modern publishing platform</h1>
          <h3>Grow your audience and build your online brand</h3>
        </div>
        <div class="main__buttons">
          <button href="#" class="start_for_free">Start for Free</button>
          <button href="#" class="learn_more">Learn More</button>
        </div>
      </div>
    </div>
  </header>

JS

document.getElementById('hamburger').addEventListener('click', showNav);

function showNav() {
    
    const navMenu = document.getElementById('nav_bar');

    if(navMenu.style.display == 'none') {
        navMenu.style.display = 'block';
    } else {
        navMenu.style.display = 'none'
    }

}

export { showNav }

webpack.dev

const path = require("path");
const common = require("./webpack.common")
const { merge } = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");


module.exports = merge(common, {
    mode: 'development',
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, "dist")
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "./index.html",
            inject: 'body'
        }),
    ],
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    }
});

webpack.prod

const path = require("path");
const common = require("./webpack.common")
const { merge } = require("webpack-merge");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");



module.exports = merge(common, {
    mode: 'production',
    output: {
        filename: '[name].[contenthash].bundle.js',
        path: path.resolve(__dirname, "dist")
    },
    optimization: {
        minimizer: [
            new OptimizeCssAssetsPlugin(), new TerserPlugin(), new HtmlWebpackPlugin({
                template: "./src/index.html",
                filename: "./index.html"
            }),
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({ filename:"[name].[contenthash].css" }),
        new CleanWebpackPlugin()
    ],
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            }
        ]
    }
});

webpack.common

const path = require("path");
const webpack = require("webpack");


module.exports = {
    output: {
        filename: 'main.[contentHash].js',
        path: path.resolve(__dirname, "dist")
    },
    devtool: 'source-map',
    entry: {
        main: "./src/js/index.js",
        vendor: "./src/vendor.js"
    },
    module: {
        rules: [
            {
                test: '/\.js$/',
                exclude: /node_modules/,
                loader: "babel-loader"
            },
            {
                test: /\.html$/,
                use: ["html-loader"]
            },
            {
                test: /\.(svg|png|jpeg|gif)$/,
                use: {
                    loader: "file-loader",
                    options: {
                        name: "[name].[hash].[ext]",
                        outputPath: "imgs"
                    }
                }
            }
        ]
    }
}

标签: javascripthtmlwebpack

解决方案


getElementById方法:

  • 它使用给定的 id 创建一个变量。
  • 如果多个元素具有相同的 ID (这是非常糟糕的做法,不要这样做),它会选择第一项。
  • 如果没有元素具有 ID,则它等于 null。

单击“运行代码片段”按钮,然后单击“测试”,以查看此错误的示例。

<p id="dontchangeme">Click the button!</p>
<button onclick="document.getElementById('changeme').innerHTML='done!';">Test</button>

你得到控制台中抛出的错误。

因此,请确保存在“汉堡包”ID。

如果 id 存在,一切正常:

<p id="changeme">Click the button!</p>
<button onclick="document.getElementById('changeme').innerHTML='done!';">Test</button>

你没有 id hamburger,你只有 id hambuger。更改hambugerhamburger,它应该可以正常工作。


推荐阅读