close

[Solved] cannot read properties of null (reading ‘addEventListener’)

I am trying to add addEventListener to my button but somehow I am facing the following error: cannot read properties of null (reading ‘addEventListener’) in javascript. We are going to Learn about All Possible Solutions So Lets Get Start with This Article.

How cannot read properties of null (reading ‘addEventListener’) Error Occurs?

I am trying to add addEventListener to my button but somehow I am facing the following error:

cannot read properties of null (reading 'addEventListener')

So here I am writing all the possible solutions that I have tried to resolve this error.

How To Solve cannot read properties of null (reading ‘addEventListener’) Error?

  1. How To Solve cannot read properties of null (reading 'addEventListener') Error?

    To Solve cannot read properties of null (reading 'addEventListener') Error If You are Defining Script Before your button then You will face this error. So All You need to so is Just Define Your Script After Button. And Now, Your error will be solved.

  2. cannot read properties of null (reading 'addEventListener')

    To Solve cannot read properties of null (reading 'addEventListener') Error Here is what Caused this error? When you are trying to add addEventListener on the null. and That's why this error occurs. So You can use if Statement. So Using if Error will be solved.

Solution 1: Use if statement

Here is what Caused this error? When you are trying to add addEventListener on the null. and That’s why this error occurs. So You can use if Statement Just like this.

const upvoteBtn = document.getElementById('vote-up');
console.log(upvoteBtn); // null

if (btn) {
  upvoteBtn.addEventListener('click', () => {
    console.log('Button is clicked');
  });
}

So Using if Error will be solved.

Solution 2: Define Script After Button

If You are Defining Script Before your button then You will face this error. So All You need to so is Just Define Your Script After Button Just like This.

<!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">
</head>
<body>

    <button id="vote-up">Up Vote This Answer</button>

    <!-- This is Right Method To Load Script After Button -->
    <script src="my_script.js"></script>
    
</body>
</html>

And Now, Your error will be solved.

Conclusion

It’s all About this error. Hope We solved Your error. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also, Read

Leave a Comment