Cannot read property addeventlistener of null как исправить

I’ve a collection of quotes along with names. I’m using update button to update the last quote associated with a specific name but on clicking update button it’s not updating. I’m including code below for server.js file and external js file (main.js).

main.js (external js)

var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})
.then(res =>{
    if(res.ok) return res.json()
})
.then(data =>{
    console.log(data);
    window.location.reload(true);
})
})
}

server.js file

app.put('/quotes', (req, res) => {
  db.collection('quotations').findOneAndUpdate({name: 'Vikas'},{
    $set:{
        name: req.body.name,
        quote: req.body.quote
    }
  },{
    sort: {_id: -1},
    upsert: true
  },(err, result) =>{
    if (err) return res.send(err);
    res.send(result);
  })

})

The “cannot read property ‘addEventListener’ of null” error occurs in JavaScript when you try to call the addEventListener() method on an element that cannot be found in the DOM. This happens for two main reasons:

  1. Accessing the addEventListener() method on an element absent from the DOM.
  2. Inserting the script tag referencing the JavaScript file at a point above the declaration of the DOM element in the HTML.

We’ll learn how to handle the error for these two scenarios in this article.

The "cannot read property 'addEventListener' of null" error occurring in JavaScript.

Cause 1: Accessing addEventListener() on an element not present in the DOM

index.js

const btn = document.getElementById('does-not-exist');

console.log(btn); // null

// ❌ Cannot read property 'addEventListener' of null
btn.addEventListener('click', () => {
  alert('You clicked the button');
});

When a method like getElementById() or querySelector() method is used to search for an element that doesn’t exist in the DOM, it returns null. And attempting to call the addEventListener() method on a null value will cause the error.

Solve: Ensure correct selector

To fix the “cannot read property ‘addEventListener’ of null” error, make sure the selector used the access the element is properly defined. Ensure that there are no mistakes in the ID or class name, and the correct symbols are used.

Solve: Check for null

To fix the “cannot read property ‘addEventListener’ of null” error, check that the element is not null before calling the addEventListener() method on it.

We can do this with an if statement:

const btn = document.getElementById('does-not-exist');

console.log(btn); // null

// ✅ Check if element exists before calling addEventListener()
if (btn) {
  // Not called
  btn.addEventListener('click', () => {
    alert('You clicked the button');
  });
}

When a value is placed in between the brackets of an if statement, it is coerced to a Boolean before being evaluated, i.e., truthy values become true, and falsy values become false. null is a falsy value, so it is coerced to false and the code in the if statement block is never run.

Note: In JavaScript, there are six falsy values: undefined, null, NaN, 0, '' (empty string) and false. Every other value is truthy.

We can also use the optional chaining operator (?.) to check if the element is null.

const btn = document.getElementById('does-not-exist');

console.log(btn); // null

// ✅ Check if element exists before calling addEventListener()

// Not called
btn?.addEventListener('click', () => {
  alert('You clicked the button');
});

The optional chaining operator (?.) is null-safe way of accessing a property or calling a method of an object. If the object is nullish (null or undefined), the operator prevents the member access and returns undefined instead of throwing an error.

Cause 2: Inserting the script tag above the DOM element

Another common cause of this error is placing the <script> tag referencing the JavaScript file at a point above where the target element is declared.

For example, in this HTML markup:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>
    <!-- ❌ Script is run before button is declared -->
    <script src="index.js"></script>
  </head>
  <body>
    <button id="btn">Sign up</button>
  </body>
</html>

the script tag is placed in the head tag, above where the button element is declared, so the index.js file will not be able to access the button element.

index.js

const btn = document.getElementById('btn');

console.log(btn); // null

// ❌ TypeError: Cannot read properties of null
btn.addEventListener('click', () => {
  alert('You clicked the button');
});

Solve: Move script tag to bottom of body

To fix the error in this case, move the script tag to the bottom of the body, after all the HTML elements have been declared.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body>
    <button id="btn">Sign up</button>

    <!-- ✅ Script is run after button is declared -->
    <script src="index.js"></script>
  </body>
</html>

Now the index.js script file will have access to the button element and all the other HTML elements, because they would have already been declared when the script is run.

index.js

const btn = document.getElementById('btn');

console.log(btn); // HTMLButtonElement object

// ✅ Works as expected
btn.addEventListener('click', () => {
  alert('You clicked the button');
});

Solve: Access element in DOMContentLoaded event listener

Another way to fix the “cannot read property ‘addEventListener’ of null” error in JavaScript is to add a DOMContentLoaded event listener to the document, and access the element in this listener. With this approach it won’t matter where we place the script in the HTML.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>

    <!-- Script placed above element accessed -->
    <script src="index.js"></script>
  </head>
  <body>
    <button id="btn">Sign up</button>
  </body>
</html>

The DOMContentLoaded event is fired when the browser has fully loaded the HTML, and the DOM tree has been built, but external resources like images and stylesheets may not have loaded. So regardless of where we place the script, the code in the listener is only called after all the declared HTML elements have been added to the DOM.

index.js

document.addEventListener('DOMContentLoaded', () => {
  const btn = document.getElementById('btn');

  console.log(btn); // HTMLButtonElement object

  // ✅ Works as expected
  btn.addEventListener('click', () => {
    alert('You clicked the button');
  });
});

Conclusion

We can fix the “cannot read property addEventListener’ of null” error in JavaScript by ensuring that the correct selector is defined, adding a null check to the element before calling addEventListener(), moving the script tag to the bottom of the body, or accessing the element in a DOMContentLoaded event listener added to the document.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

Кто подскажет как исправить.
С этим скриптом выбивает ошибку и крашит весь остальной код после него https://codepen.io/anon/pen/MqgWwR
Ошибка: Uncaught TypeError: Cannot read property ‘addEventListener’ of null

Я обернул скрипт в
window.onload=function() {
мой код
}
Теперь просто не крашится остальной код, но ошибка все равно осталась.


  • Вопрос задан

    более трёх лет назад

  • 7244 просмотра

Очевидно, потому, что в вашем HTML-коде нет элемента с селектором input[name=inp-price]
По стандарту селектор должен выглядеть как input[name="inp-price"]

Пригласить эксперта


  • Показать ещё
    Загружается…

20 мая 2023, в 15:39

1000 руб./в час

20 мая 2023, в 15:37

750 руб./в час

20 мая 2023, в 14:47

5000 руб./за проект

Минуточку внимания

I’ve a collection of quotes along with names. I’m using update button to update the last quote associated with a specific name but on clicking update button it’s not updating. I’m including code below for server.js file and external js file (main.js).

main.js (external js)

var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})
.then(res =>{
    if(res.ok) return res.json()
})
.then(data =>{
    console.log(data);
    window.location.reload(true);
})
})
}

server.js file

app.put('/quotes', (req, res) => {
  db.collection('quotations').findOneAndUpdate({name: 'Vikas'},{
    $set:{
        name: req.body.name,
        quote: req.body.quote
    }
  },{
    sort: {_id: -1},
    upsert: true
  },(err, result) =>{
    if (err) return res.send(err);
    res.send(result);
  })

})

If you use the script tag before declaring DOM elements, you may get the error “Cannot read property ‘addeventlistener’ of null” in JavaScript. So how to fix it? Read this article till the end to find the best answer.

Cause of the error “Cannot read property ‘addEventlistener’ of null” in js

There are two main situations where the error occurs:

  1. Using the script tag before declaring DOM elements.
  2. Trying to access the addEventListener() method on a non-exist DOM element.

Most users who encounter the error will fall into the second case.

How do we fix the error?

Solution1: Move the Script tag to the bottom of the body

To avoid errors, you must place the script tag at the end of the body. This will make your javascript code work with all the HTML elements declared above. The example below is a harmful code when we put the scripts at the top of the body.

<!DOCTYPE html>
<html>
<title>Demo</title>
<head>
</head>
<body>

       <script>
           const myBtn = document.getElementById('demoBtn');
           myBtn.addEventListener("click", myFunction);

	         function myFunction() {
 		           console.log('Example 1')
           }
       </script>

       <button id="demoBtn">My Example</button>

</body>
</html>

If your code is like the example above, you won’t get the desired results. The reason is that the ‘button’ element is placed after the scripts, so when we access it through the getElementById() method, the return result will be ‘null’. 

Output:

Please modify the code to the following. You will see the result exactly as you want.

<!DOCTYPE html>
<html>
<title>Demo</title>
<head>
</head>
<body>
        <button id="demoBtn">My Example</button>

        <script>
           const myBtn = document.getElementById('demoBtn');
           myBtn.addEventListener("click", myFunction);

	         function myFunction() {
 		          console.log('Example 1')
           }
        </script>

</body>
</html>

Output:

Now the method getElementById() can find the element ‘button’ with the id = ‘demoBtn’ and display the correct result instead of the value ‘null’ like above.

Solution 2: Use conditional statements to check for the element’s existence

To prevent you from accidentally accessing an HTML element that does not exist, I suggest using a conditional statement to check for the existence of the element before you want to work with it.

<!DOCTYPE html>
<html>
<title>Demo</title>
<head>
</head>
<body>

        <button class="btn btn-primary" id="demoBtn">Check</button>
        <p id="demo"></p>

        <script>

        	const myBtn = document.getElementById('demoBtn');
        	if(myBtn){
            		myBtn.addEventListener("click", myFunction1);
       	 }
        
        	function myFunction1() {
                document.getElementById("demo").innerHTML = "Button Clicked, Element Found!";
        	}
         </script>

</body>
</html>

Output:

In the example, we’ll add a conditional statement to check if we get HTML element through method getElementById() or not. If the result is not null, we attach an event handler to an element – specifically the method addEventListener

Using the if statement will help you avoid the error “cannot read property ‘addEventlistener’ of null“. 

Now, when you pass an incorrect identifier to getElementById(), the addEventListener() method will not be called because of the null value, and the error will not occur.

Summary

In summary, I helped you learn how to fix the error “cannot read property ‘addEventlistener’ of nullin js through a few examples above. Thanks, and I hope this information is helpful to you.

Maybe you are interested:

  • Cannot read property ‘style’ of Null in JavaScript
  • Cannot set property ‘innerHTML’ of Null in JavaScript
  • Cannot read Properties of Undefined in JavaScript
  • Cannot find module ‘@babel/core’ error

My name’s Christopher Gonzalez. I graduated from HUST two years ago, and my major is IT. So I’m here to assist you in learning programming languages. If you have any questions about Python, JavaScript, TypeScript, Node.js, React.js, let’s contact me. I will back you up.

Name of the university: HUST
Major: IT
Programming Languages: Python, JavaScript, TypeScript, Node.js, React.js

Добавить комментарий