Register Login

Uncaught TypeError cannot read property 'addeventlistener' of null

Updated May 15, 2020

In JavaScript, a very common error is the Uncaught TypeError Cannot read property 'addeventlistener' of null. This error occurs when JavaScript is not able to add an event listener to an element for performing a function. It can also occur when JS cannot find the element by using its id through the getElementById() function.

The solution to this problem is to place the JavaScript code after the HTML code so that it loads after HTML. Let us look at this problem in detail.

Error Code Example:

<html><head>
<title>Javascript Function</title>
<script>
	const bclick = document.getElementById('clickme');
	bclick.addEventListener('click', function red () { 
		mydiv.style.backgroundColor = 'red';
	});
</script>
</head>
<body>
	<div id="clickme">Fill Color Red</div>
	<div id="mydiv" style="width: 100%; height: 200px;"></div>
</body></html>

In the above example, we are storing the value of div with an ID "clickme" in the variable "bclick". But this div is declared in the <body> tag. The script is placed within the head tag. We know that JavaScript compiles from top to bottom. So, while executing this script div "clickme" not found by the compiler and the TypeError error is returned.

To fix this error we can move the JavaScript code below body tag or we can use jQuery document.ready method.

Uncaught TypeError cannot read property 'addeventlistener' of null

Solution:

<html><head>
<title>Javascript Function</title>
</head>
<body>
	<div id="clickme">Fill Color Red</div>
	<div id="mydiv" style="width: 100%; height: 200px;"></div>
<script>
	const bclick = document.getElementById('clickme');
	bclick.addEventListener('click', function red () { 
		mydiv.style.backgroundColor = 'red';
	});
</script>
</body></html>

By Using jQuery Library

<html><head>
<title>Javascript Function</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
	const bclick = document.getElementById('clickme');
	bclick.addEventListener('click', function red () {
		mydiv.style.backgroundColor = 'red';
	});
});
</script>
</head>
<body>
<div id="clickme">Fill Color Red</div>
<div id="mydiv" style="width: 100%; height: 200px;"></div>
</body></html>

In the above example, we have used the jquery ready() method. This is used to make a function available after the document is loaded. The code you write inside the $(document ).ready() method will run once the DOM is ready to execute JavaScript code. Using this method, we can avoid the Uncaught TypeError.

Conclusion:

Make sure that the latest version of jQuery is used in your code. And place it before the script code. Also, ensure that the tags are arranged properly in your HTML code to avoid errors.


×