Skip to content
Advertisement

Getting a “Uncaught TypeError: Cannot read property ‘addEventListener’ of null”

I’m practicing my vanilla JS and trying to create dynamic elements. I came across some interesting behavior. I am simply creating a button, click it and then have it render onto the DOM. But then I want to create another event that mouses over the h1 elements and changes the color, however I get a “Uncaught TypeError: Cannot read property ‘addEventListener’ of null”. Why is this showing up as null if there is a h1 on the DOM and why does it now say cannot read property “addEventListener” of null?

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Creating Dynamic Elements</title>
</head>
<body>
  
</body>
</html>

JavaScript

// const h1 = document.querySelectorAll('h1');  
const button = document.createElement('button');
button.textContent = "Click me";
document.querySelector('body').appendChild(button);

button.addEventListener('click', function() {
  const h1 = document.createElement('h1');
  h1.textContent = 'Hello World!';
  document.querySelector('body').appendChild(h1);
});

document.querySelector('h1').addEventListener('mouseover', function() {
  alert("It works!");
});



Advertisement

Answer

Add your h1 event listener inside the function since there’s no h1 on load.

const button = document.createElement('button');
button.textContent = "Click me";
document.querySelector('body').appendChild(button);

button.addEventListener('click', function() {
  const h1 = document.createElement('h1');
  h1.textContent = 'Hello World!';
  document.querySelector('body').appendChild(h1);

  h1.addEventListener('mouseover', function() {
    alert("It works!");
  });
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement