addEventListener がエラーになる
addEventListenerにエラーが出てしまう
javascriptを使ってドロップダウンメニューを作成使用としているのですが、
addEventListenerがうまく機能せず、ドロップダウンメニューができず困っている状態です。
原因がわからない為、何卒ご教授を宜しくお願い致します。
発生している問題・エラー
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
デベロッパーツールに表示されているエラーです。
ある動画を参考にそのままコードを記載しているのですが、エラーが出てしまいます。
該当するソースコード
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>タイトル</title>
<link rel = "stylesheet" href = "CSS/styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css" integrity="sha384-HzLeBuhoNPvSl5KYnjx0BT+WB0QEEqLprO+NBkkk5gbc67FTaL7XIGa2w1L0Xbgc" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@500&display=swap" rel="stylesheet">
</head>
<body>
<header>
<div class = "header-wrapper">
<div class = "container">
<div class = "header-contents">
<div class = "header-main">
<!-- ロゴ -->
<div class = "header-logo">
<img src = "picture/picture1.jpg" width="180px">
</div>
<!-- ヘッダーメニュー -->
<ul class = "menu">
<li>
<a href = "#">メニュー1</a>
<ul>
<li><a href = "#">child menu</a></li>
<li><a href = "#">child menu</a></li>
<li><a href = "#">child menu</a></li>
</ul>
</li>
<li>
<a href = "#">メニュー2</a>
<ul>
<li><a href = "#">child menu</a></li>
<li><a href = "#">child menu</a></li>
<li><a href = "#">child menu</a></li>
</ul>
</li>
<li>
<a href = "#">メニュー3</a>
<ul>
<li><a href = "#">child menu</a></li>
<li><a href = "#">child menu</a></li>
<li><a href = "#">child menu</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</header>
<main></main>
<script src = "JS/main.js"></script>
</body>
</html>
header {
position: relative;
height: 130px; }
.header-wrapper {
height: 100%; }
.header-contents {
height: 130px; }
.header-main {
height: 100%;
display: flex;
justify-content: space-between; }
.menu ul {
display: none; }
.menu ul.active {
display: block; }
a, a::after, a::before {
box-sizing: border-box; }
a {
color: black;
text-decoration: none; }
.menu a {
transition: 0.3s; }
.menu a:hover {
opacity: 0.7; }
.menu > li > a {
display: block;
padding: 10px;
background-color: white; }
.menu > li > ul a {
display: block;
padding: 10px;
background-color: white; }
const parentMenu = document.querySelectorAll(".menu > li > a");
for(let i = 0; i = parentMenu.length; i++){
parentMenu[i].addEventListener("click", function() {
this.nextElementSibling.classList.toggle("active");
});
};
デベロッパーツールにて、
javascriptのaddEventListenerの部分からfunction(){ の所にかけて
波線がひかれ、❌と表示されています。
宜しくお願い致します。
0 likes