Ошибка uncaught typeerror 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);
  })

})

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.

  • 031071

На codepen.io/dudleystorey/pen/JDphy всё отлично работает. Взял скопировал себе на локальную машины, а мне в ответ ошибка «Uncaught TypeError: Cannot read property ‘addEventListener’ of null (anonymous function) @ script.js:4
» и перехода нет…


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

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

  • 43731 просмотр

$(document).ready(function() {
            setInterval(window.onload = function(){
                   ...тут ваш код
            });
        });

js в конце, перед </body>

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

Проблему решил перетащив js код из отдельного файла script.js в index.html…. Код засунул в body под … Бред…

Вероятно, код срабатывал до загрузки элемента id=»inked-painted».

Видимо у вас JS код находиться либо в теге head, либо в теге body, но перед элементом к которому присвоен JS код. Чтобы такого не было надо ставить JS код в самом конце перед закрывающимся тегом body.

А как быть, если Js-код webpack подставляется куда ему надо?


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

13 июн. 2023, в 18:02

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

13 июн. 2023, в 17:53

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

13 июн. 2023, в 17:47

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

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

As a JavaScript developer, you might encounter different types of errors while running a JavaScript program.

One of the most common errors that you may get is the “Uncaught TypeError: Cannot Read Property ‘addEventListener’ of Null” error.

In this article, we will discuss the causes and how to fix the cannot read property ‘addeventlistener’ of null.

Why the cannot read property of null reading addeventlistener error occur?

The “cannot read property of null reading addeventlistener” error message typically occurs in JavaScript because you are trying to call the addEventListener() method on an element which is can’t be found in the DOM.

Before we discuss the solutions, it is necessary to understand first the causes of the error.

Here are some of the reasons why you may encounter this error:

  • You are trying to add an event listener to a variable that is null or undefined.
  • Adding an event listener to an element that do not exist in the DOM.
  • It is possible that you are using the wrong variable name or element ID in your code.

We will learn how to handle this error:

error message Uncaught typeerror: cannot read property 'addeventlistener' of null

[SOLVED] Uncaught typeerror: cannot read property ‘addeventlistener’ of null

Here are the solutions to solve the cannot read property ‘addeventlistener’ of null error.

Solution 1: Correct Selector

The first solution to solve this error is to ensure that the selector being used can access the element that is correctly defined.

You will make sure that there are no mistakes in the ID or class name, and the proper symbols are being used.

Solution 2: Checking for Null by using if Statement

The second solution to solve the error is to check the element which is not null before calling the addEventListener() method on it.

For example for using an If Statement:

const btn = document.getElementById('my-button');

console.log(btn); // <button id="my-button">Click me</button>


if (btn) {
  btn.addEventListener('click', () => {
    alert('You clicked the button');
  });
}

In this example code, the variable btn is set to the element with the ID “my-button”.

If such an element exists in the HTML document, btn will be assigned a reference to that element.

Which can then be used to attach an event listener to it.

In addition, we can also use the optional chaining operator.

Let’s take a look at the example:

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

console.log(myButton); // null


myButton?.addEventListener('click', () => {
  alert('You clicked the button');
});

In this example code, The myButton variable is used to store a reference to the button element with the ID does-not-exist (which does not exist in the document).

The console.log statement logs the value of the myButton variable, which will be null since the element does not exist.

The myButton?.addEventListener statement adds a click event listener to the myButton element, but only if the myButton variable is not null.

Solution 3: Moving script tag to bottom of the body

The third solution to solve this error by moving the script tag to bottom of the body.

After all the HTML elements have been declared.

For example:

In your index.html file:


<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Typeerror Tutorial</title>
  </head>
  <body>
    <button id="btn">Rgeistration</button>

    <script src="index.js"></script>
  </body>
</html>

The index.js file can access the button and other HTML elements since they have already been declared when the script runs.

For index.js file:

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

console.log(button); 

button.addEventListener('click', () => {
  alert('You clicked the button');
});

The button variable is assigned to the HTML element with the ID of btn.

Then, the code will logs the button variable to the console.

Finally adds a click event listener to the button element that will show an alert when clicked.

Solution 4: Accessing element in DOMContentLoaded event listener

The last solution to fix the “cannot read property ‘addEventListener’ of null” error in JavaScript.

We can add a DOMContentLoaded event listener to the document and access the element in this listener.

By doing this, the script can be placed anywhere in the HTML without causing issues.

For example:

Copy this code into your file in index.html:

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

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

Copy this code in your file in index.js:

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

  console.log(myButton);


  myButton.addEventListener('click', () => {
    alert('You clicked the button');
  });
});

This code sets up an event listener that is to awaits for the web page to finish loading (the DOMContentLoaded event).

If the page has been finished loading, it looks for an HTML button element with the ID “btn”.

And it will store it in a variable called btn (or whatever name you choose to use).

Additional Resources

Visit the link below to understand more about on how to handle the Typeerror you may encountered:

  • Typeerror: callback is not a function
  • Uncaught typeerror at app.js: i is undefined
  • Typeerror: ‘dict_keys’ object is not subscriptable
  • Typeerror: ‘tuple’ object does not support item assignment

Conclusion

In conclusion, the “Uncaught TypeError: Cannot Read Property ‘addEventListener’ of Null” error is a common error which is easy to solve with the correct understanding.

Through following the solutions mentioned in this article, you can quickly identify and resolve the error in your JavaScript code.

FAQs

What is the “Uncaught TypeError: Cannot Read Property ‘addEventListener’ of Null” error?

This error occurs when you’re trying to add an event listener to a variable that is either null or undefined.

Why do I get the “Uncaught TypeError: Cannot Read Property ‘addEventListener’ of Null” error?

You get this error because you are trying to add an event listener to a variable.

Понравилась статья? Поделить с друзьями:
  • Ошибка unarc dll как исправить dll files
  • Ошибка unable to set graphics mode
  • Ошибка unarc dll вернул код ошибки 14 как исправить
  • Ошибка unable to save torrent to
  • Ошибка unarc dll вернул код ошибки 12 windows 10