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?
JavaScript
x
15
15
1
HTML
2
<!DOCTYPE html>
3
<html lang="en">
4
<head>
5
<meta charset="UTF-8">
6
<meta http-equiv="X-UA-Compatible" content="IE=edge">
7
<meta name="viewport" content="width=device-width, initial-scale=1.0">
8
<title>Creating Dynamic Elements</title>
9
</head>
10
<body>
11
12
</body>
13
</html>
14
15
JavaScript
1
20
20
1
JavaScript
2
3
// const h1 = document.querySelectorAll('h1');
4
const button = document.createElement('button');
5
button.textContent = "Click me";
6
document.querySelector('body').appendChild(button);
7
8
button.addEventListener('click', function() {
9
const h1 = document.createElement('h1');
10
h1.textContent = 'Hello World!';
11
document.querySelector('body').appendChild(h1);
12
});
13
14
document.querySelector('h1').addEventListener('mouseover', function() {
15
alert("It works!");
16
});
17
18
19
20
Advertisement
Answer
Add your h1 event listener inside the function since there’s no h1 on load.
JavaScript
1
13
13
1
const button = document.createElement('button');
2
button.textContent = "Click me";
3
document.querySelector('body').appendChild(button);
4
5
button.addEventListener('click', function() {
6
const h1 = document.createElement('h1');
7
h1.textContent = 'Hello World!';
8
document.querySelector('body').appendChild(h1);
9
10
h1.addEventListener('mouseover', function() {
11
alert("It works!");
12
});
13
});