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

为closeBtn绑定addEventListener时触发TypeError错误求助

Fixing "Uncaught TypeError: closeBtn.addEventListener is not a function"

Hey there! Let's break down what's going on here and fix that error.

The Root Cause

The problem lies in how you're selecting the close button:

var closeBtn = document.getElementsByClassName('closeBtn');

getElementsByClassName() returns an HTMLCollection—a collection-like object containing all elements that match the class, not a single DOM element. Even if only one element has that class, you can't call addEventListener() directly on the collection because it doesn't have this method built in.

Quick Fixes

Here are two straightforward ways to resolve this:

1. Target the first element in the collection

Since your HTML only has one .closeBtn, you can grab the first item (index 0) from the returned collection:

// Closing
closeBtn[0].addEventListener('click', closeModal);

2. Use querySelector() instead

querySelector() returns the first single element that matches the selector, which is exactly what you need here. Replace your closeBtn declaration with:

var closeBtn = document.querySelector('.closeBtn'); // Close Button Element

Then you can use addEventListener() normally:

closeBtn.addEventListener('click', closeModal);

Bonus Fix: Typo in closeModal()

You also have a small typo in your closeModal function—you're referencing modal instead of modal2 (the variable you defined for your modal):

function closeModal() {
  modal2.style.display = "none"; // Changed from "modal" to "modal2"
}

Full Corrected Code

Here's the fixed JavaScript code put together:

//View Faculty Schedule MODAL SCRIPT//
var modal2 = document.getElementById('view-modal'); //Get Modal Element
var modalBtn = document.getElementById('searchfaculty'); //Button Element
var closeBtn = document.querySelector('.closeBtn'); // Close Button Element

//opening
modalBtn.addEventListener('click', openModal);
//closing
closeBtn.addEventListener('click', closeModal);

function openModal() {
  modal2.style.display = "block";
}

function closeModal() {
  modal2.style.display = "none";
}

That should get your modal closing properly without errors!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:45:39