Uncaught TypeError: Cannot read property ‘addEventListener’ of undefined error in my JS file

Tags: , ,



    <div class="card-body">
                <hr>
                <h5 class="card-title" id = "tasks-title">Todo's</h5>
                <div class="form-row">
                        <div class="form-group col-md-6">
                            <input class="form-control" type="text" name="filter" id = "filter" placeholder="Search A Todo">
                        </div>
                </div>
  <div>

I gave my HTML codes on the top. JS Codes are on the down:

const cardBody = document.querySelectorAll(".card-body")[2];

const title = document.querySelector("#tasks-title");

cardBody.addEventListener("mouseenter",run);
cardBody.addEventListener("mouseleave", run);

function run(e) {
 console.log(e.type);}

In this case, When I hover over the cardBody element, the output must write “mouseenter”. And when I leave with the mouse, the output must “mouseover”. However, I get an error Uncaught TypeError: Cannot read property ‘addEventListener’ of undefined. I searched everywhere about this problem, but there is no solution to my mistake.

Answer

There is only one element that has the class name card-body. So you should indicate document.querySelectorAll(".card-body")[0]

const cardBody = document.querySelectorAll(".card-body")[0];

const title = document.querySelector("#tasks-title");

cardBody.addEventListener("mouseenter", run);
cardBody.addEventListener("mouseleave", run);

function run(e) {
  console.log(e.type);
}
<div class="card-body">
  <hr>
  <h5 class="card-title" id="tasks-title">Todo's</h5>
  <div class="form-row">
    <div class="form-group col-md-6">
      <input class="form-control" type="text" name="filter" id="filter" placeholder="Search A Todo">
    </div>
  </div>
<div>


Source: stackoverflow