Cannot read properties of null reading classlist ошибка

В отладчике горит ошибка, не понимаю в чем проблема, в js опыта не много пока что(

Uncaught TypeError: Cannot read properties of null (reading 'classList')
at enableButton (validate.js:82:17)
at toggleButtonState (validate.js:72:5)
at setEventListeners (validate.js:36:3)
at validate.js:59:37
at Array.forEach (<anonymous>)
at enableValidation (validate.js:59:12)
at validate.js:86:1

Вот код:

/* Выводим сообщение об ошибке и меняем стиль поля ввода на содержащий ошибку */
const showInputError = (formElement, inputElement, errorMessage, config) => {
  const errorElement = formElement.querySelector(`.${inputElement.id}-error`);
  inputElement.classList.add(config.inputErrorClass);
  errorElement.textContent = errorMessage;
  errorElement.classList.add(config.errorClass);
};

/* Скрываем сообщение об ошибке и меняем стиль поля ввода на нормальный */
const hideInputError = (formElement, inputElement, config) => {
  const errorElement = formElement.querySelector(`.${inputElement.id}-error`);
  inputElement.classList.remove(config.inputErrorClass);
  errorElement.classList.remove(config.errorClass);
  errorElement.textContent = "";
};

/* Функция проверяет валидность поля */
const checkInputValidity = (formElement, inputElement, config) => {
  if (!inputElement.validity.valid) {
    showInputError(
      formElement,
      inputElement,
      inputElement.validationMessage,
      config
    );
  } else {
    hideInputError(formElement, inputElement, config);
  }
};

const setEventListeners = (formElement, config) => {
  const inputList = Array.from(
    formElement.querySelectorAll(config.inputSelector)
  );
  const buttonElement = formElement.querySelector(config.submitButtonSelector);
  toggleButtonState(inputList, buttonElement, config);
  inputList.forEach((inputElement) => {
    inputElement.addEventListener("input", () => {
      checkInputValidity(formElement, inputElement, config);
      toggleButtonState(inputList, buttonElement, config);
    });
  });
};

const validateFormNow = (formElement, config) => {
  const inputList = Array.from(
    formElement.querySelectorAll(config.inputSelector)
  );
  const buttonElement = formElement.querySelector(config.submitButtonSelector);
  toggleButtonState(inputList, buttonElement, config);
  inputList.forEach((inputElement) => {
    checkInputValidity(formElement, inputElement, config);
  });
};

/* Включаем валидацию для всех форм */
const enableValidation = (config) => {
  const formList = Array.from(document.querySelectorAll(config.formSelector));
  formList.forEach((formElement) => setEventListeners(formElement, config));
};

/* Проверяем есть ли среди полей ввода формы, которые не проходят валидацию */
const hasInvalidInput = (inputList) => {
  return inputList.some((inputElement) => !inputElement.validity.valid);
};

/* Смена состояния кнопки с активной на неактивную */
function toggleButtonState(inputList, buttonElement, config) {
  if (hasInvalidInput(inputList)) {
    disableButton(buttonElement, config);
  } else {
    enableButton(buttonElement, config);
  }
}

function disableButton(buttonElement, config) {
  buttonElement.classList.add(config.inactiveButtonClass);
  buttonElement.setAttribute("disabled", "");
}

function enableButton(buttonElement, config) {
  buttonElement.classList.remove(config.inactiveButtonClass);
  buttonElement.removeAttribute("disabled");
}

enableValidation(validationConfig);

This guide will help you understand the ‘Cannot Read Property ClassList of Null’ error, its causes, and step-by-step solutions to fix the issue. We will also discuss some frequently asked questions related to this error.

Table of Contents

  1. Understanding the ‘Cannot Read Property ClassList of Null’ Error
  2. Common Causes of the Error
  3. Step-by-Step Solutions to Fix the Error
  4. FAQs
  5. Related Links

Understanding the ‘Cannot Read Property ClassList of Null’ Error

The ‘Cannot Read Property ClassList of Null’ error is a common JavaScript error that occurs when a script attempts to access an element’s classList property, but the element is null. This means that the element either does not exist or cannot be found by the script for some reason.

Common Causes of the Error

Some of the most common causes of the ‘Cannot Read Property ClassList of Null’ error are:

  1. Incorrect element selector: If the script is using an incorrect or outdated element selector, it will not be able to find the element in the DOM, resulting in the error.
  2. Script execution timing: If the script is executed before the target element is loaded in the DOM, it will not be able to find the element, leading to the error.
  3. Dynamically loaded elements: In some cases, the elements are loaded into the page dynamically, which means that they may not be available in the DOM when the script is executed.

Step-by-Step Solutions to Fix the Error

Solution 1: Check and Update the Element Selector

Verify that the element selector used in the script is correct and up-to-date. This can be done by checking the HTML source code and confirming that the selector matches the actual element.

Update the element selector in the script if it is incorrect or outdated.

Solution 2: Ensure Script Execution Timing

Make sure that the script is executed after the DOM is fully loaded. This can be done by placing the script at the bottom of the HTML file, just before the closing </body> tag.

Alternatively, you can use the DOMContentLoaded event to ensure that the script is executed after the DOM is fully loaded, like this:

document.addEventListener('DOMContentLoaded', function() {
    // Your script code here
});

Solution 3: Handle Dynamically Loaded Elements

If the elements are loaded dynamically, you can use the MutationObserver API to watch for changes in the DOM and execute the script when the desired element is added. This can be done like this:

const observer = new MutationObserver(function(mutations) {
    const targetElement = document.querySelector('.my-element');
    
    if (targetElement) {
        // Your script code here
        observer.disconnect();
    }
});

observer.observe(document.body, { childList: true, subtree: true });

FAQs

What does ‘Cannot Read Property ClassList of Null’ mean?

The ‘Cannot Read Property ClassList of Null’ error means that the script is trying to access the classList property of an element, but the element is null. This indicates that the element either does not exist or cannot be found by the script.

How can I fix the ‘Cannot Read Property ClassList of Null’ error?

To fix the error, you can follow these steps:

  1. Check and update the element selector
  2. Ensure script execution timing
  3. Handle dynamically loaded elements

Why is my script unable to find the element in the DOM?

  The script may be unable to find the element in the DOM due to the following reasons:

Incorrect element selector

Script execution timing issues

Dynamically loaded elements

How can I ensure that the script is executed after the DOM is fully loaded?

You can ensure that the script is executed after the DOM is fully loaded by placing the script at the bottom of the HTML file, just before the closing </body> tag, or by using the DOMContentLoaded event, like this:

document.addEventListener('DOMContentLoaded', function() {
    // Your script code here
});

What is the MutationObserver API and how can it help with dynamically loaded elements?

  The MutationObserver API is a JavaScript API that allows you to watch for changes in the DOM, such as elements being added or removed, attribute changes, and more. It can help with dynamically loaded elements by executing the script when the desired element is added to the DOM.

  1. Mozilla Developer Network: Element.classList
  2. Mozilla Developer Network: DOMContentLoaded
  3. Mozilla Developer Network: MutationObserver

Issue

I am having this header which on scroll, I want to change the background to a different color.
The navbar variable returns null always. Why is it so? How can I do that?
The transform:translateY is just for a small animation on scroll.

import React from 'react'
import { Navbar, Container, Nav } from 'react-bootstrap'

import { LinkContainer } from 'react-router-bootstrap'

const Header = () => {

    const navbar = document.getElementById("navbar");
    let scrolled = false;

    window.onscroll = function () {
        if (document.body.scrollTop >= 200 || document.documentElement.scrollTop >= 200) {
            navbar.classList.add('color-nav');
            if (!scrolled) {
                navbar.style.transform = 'translateY(-70px)'
            }
            setTimeout(function () {
                navbar.style.transform = 'translateY(0px)'
                scrolled = true

            }, 200)
        } else {
            navbar.classList.remove('color-nav');
            scrolled = false
        }
    };

    return (
        <div id='navbar' >
            <Navbar fixed="top" className='navbar' collapseOnSelect expand="lg"  >
                <Container>
                    <LinkContainer to='/'>
                        <Navbar.Brand className='logo' >Logo</Navbar.Brand>
                    </LinkContainer>
                    <Navbar.Toggle aria-controls="responsive-navbar-nav" />
                    <Navbar.Collapse id="responsive-navbar-nav">
                        <Nav className="me-auto">
                            <LinkContainer to='/services'>
                                <Nav.Link className='links'>Services</Nav.Link>
                            </LinkContainer>
                        </Nav>
                        <Nav>
                            <LinkContainer to='/login'>
                                <Nav.Link className='links'>Login</Nav.Link>
                            </LinkContainer>
                            <LinkContainer to='/signup'>
                                <Nav.Link className='links'>
                                    Sign Up
                                </Nav.Link>
                            </LinkContainer>
                        </Nav>
                    </Navbar.Collapse>
                </Container>
            </Navbar>
        </div >
    )
}

export default Header

enter image description here

You are going about things in what I’d like to call, «against the React way». To access the navbar element, you should be utilizing the useRef hook. This will give you an easy reference to that element through the components lifecycle.

On top of that, there are some other issues that need to be taken care of:

  • The scrolled variable not being used with useState
  • Your scroll listener not being set in a useEffect. Right now, your code would set a new listener on every re-render of your component. You want to just set it once.
  • Your scroll listener not being cleaned up.

I’ve made some changes to the code that I would hope will fix this issue for you.

import React, { useState, useRef, useEffect } from "react";
import { Navbar, Container, Nav } from "react-bootstrap";

import { LinkContainer } from "react-router-bootstrap";

const Header = () => {
  const [scrolled, setScrolled] = useState(false);
  const navRef = useRef();

  useEffect(() => {
    const handleScroll = () => {
      if (
        document.body.scrollTop >= 200 ||
        document.documentElement.scrollTop >= 200
      ) {
        navRef.current.classList.add("color-nav");

        if (!scrolled) {
          navRef.current.style.transform = "translateY(-70px)";
        }

        setTimeout(function () {
          navRef.current.style.transform = "translateY(0px)";
          setScrolled(true);
        }, 200);
      } else {
        navRef.current.classList.remove("color-nav");
        setScrolled(false);
      }
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <div id="navbar" ref={navRef}>
      <Navbar fixed="top" className="navbar" collapseOnSelect expand="lg">
        <Container>
          <LinkContainer to="/">
            <Navbar.Brand className="logo">Logo</Navbar.Brand>
          </LinkContainer>
          <Navbar.Toggle aria-controls="responsive-navbar-nav" />
          <Navbar.Collapse id="responsive-navbar-nav">
            <Nav className="me-auto">
              <LinkContainer to="/services">
                <Nav.Link className="links">Services</Nav.Link>
              </LinkContainer>
            </Nav>
            <Nav>
              <LinkContainer to="/login">
                <Nav.Link className="links">Login</Nav.Link>
              </LinkContainer>
              <LinkContainer to="/signup">
                <Nav.Link className="links">Sign Up</Nav.Link>
              </LinkContainer>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>
    </div>
  );
};

export default Header;

Answered By — Dan Zuzevich

As a Javascript programmer, you must have dealt with the “TypeError: cannot read properties of null”. 

In JavaScript, sometimes your code works completely fine, or you can get trapped in errors. This standard error occurs when one tries to read a property or call a method on a null object. In simple words, you try to access the value of null or undefined. If you are still in the same confused state, read further to find a precise solution. 

Before we move toward the answer, let’s discuss two basic terms, null and DOM, in detail, which will help you to understand the article completely.

Table of Contents
  1. What is a Null in JavaScript?
  2. What is DOM in JavaScript?
  3. Causes of the “TypeError: Cannot Read Properties of Null” Error
  4. Ways to Fix the “TypeError: Cannot Read Properties of Null” Error

What is a Null in JavaScript?

In JavaScript, a null is a primitive value, meaning the intentional absence of any object value. It is treated as a false in boolean operations. A variable with a null value is of the object type. Now understand null with the help of an example:

Code

console.log("Example of null");

let a = null;

console.log("Type of a:" ,typeof a);

console.log("A contain:" ,a);

Output

Example of null

Type of a: object

a contain: null

What is DOM in JavaScript?

Dom stands for Document Object Model in JavaScript; it is a programming interface that allows us to select, create, modify or remove elements from a document. We can easily add events to our document elements to make our page more dynamic.

Causes of the “TypeError: Cannot Read Properties of Null” Error

Normally, we face TypeError: cannot read properties of null in JavaScript when we try to access a property of the null object. Here we have a list of the most common causes of this error which are:

  1. Write wrong spelling
  2. Access property of a null object
  3. Inserting script tags before DOM elements declaration

Cause 1: Write The Wrong Spelling

When we use the wrong spell of an element id, we face this error now; let’s see an example of where we found this error.

Code

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

 

  <input type="text" id="fname" name="fname">

 <script>

var first_name = document.getElementById("name").value;

console.log(firstName)

</script>




  </body>

</html>

Output

TypeError: cannot read properties of null

In the above coding, we write fname and in the script tag, we are trying to get the id name which is not present; that’s why we face this error.

Cause 2: Accessing a Property of a Null Object

Whenever we try to access a property of a null object, we have to face the type error. Now see a simple example in which we explain this concept:

Code

console.log("Error due to Property of null");

let myvariable=null;

console.log("length of variable is:" ,myvariable.value);

Output

TypeError: cannot read properties of null

Cause 3: Inserting Script Tags Before Dom Element Declaration

The TypeError: cannot read properties of null is commonly occurs when we use the getElementById() method and pass it an id that is not present in the DOM. Usually, this error occurs when we write a script tag before the DOM element declaration. Now understand the reason for this error with the help of an example:

Code

Index.html

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

  <script src="src/script.js"></script>

  <input type="text" id="name" name="name">

   

  </body>

</html>




Script.js

var firstName = document.getElementById("name").value;

console.log(firstName)

Output

TypeError: cannot read properties of null

In this code, we write script tags before declaring DOM elements; that’s why we have TypeError.

Ways to Fix the “TypeError: Cannot Read Properties of Null” Error

Following are some solutions we can use to fix TypeError: cannot read properties of null in JavaScript.

  1. Check element id
  2. Write script tag after DOM elements declared
  3. Ways to handle null values
  4. Check if The Object Is Null or Undefined
  5. Check for Typo Errors
  6. Check if the object and property exist
  7. Use Type Checking

Now have a look at the solutions to that errors.

Solution 1: Check Element Id

It’s a good practice to always double-check the element id so you save yourself from this common type of error. Now solve the above error by simply writing the correct element id.

Code

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

 Enter your First Name:

  <input type="text" id="fname" name="fname">

 <script>

var first_name = document.getElementById("fname").value;

</script>




  </body>

</html>

Output

TypeError: cannot read properties of null

Solution 2: Write Script Tag After DOM Elements Declaration

Always try to write a script tag at the end of the body tag or after the DOM element declaration. Now understand this solution by removing the error from the above example:

Code

Index.html

<!DOCTYPE html>

<html lang="en">

  <head>

  </head>

  <body>

 Enter your First Name:

  <input type="text" id="fname" name="fname">

   <script src="src/script.js"></script>

  </body>

</html>




Script.js

var firstName = document.getElementById("fname").value;

Output

TypeError: cannot read properties of null

Solution 3: Handle Property of Null Values

When we try to access a property of a null object, we face a type error that can crash our web application. Here we have the following ways to handle null values:

  1. Use the if structure
  2. Use the ternary operator
  3. Use the try-catch block

We have four ways to handle null values; now, let’s see these four ways one by one.

We can check whether the value is null with the help of most simple way, that is, if else statement. Now let’s see a piece of code to check null values:

Code

console.log("Handle null with if else statement");

let myvariable=null;

if (myvariable) 

{

  console.log("The value of variable is:" ,myvariable.value);

} else 

{

  console.log('Your variable contains null');

}


Output

Handle null with if else statement

Your variable contains null

We can use the ternary operator to handle a null value; it is a little more complicated than if statement. Now let’s understand it with the help of an example:

Code

console.log("Handle null with the ternary operator);

let myvariable=null;

const myval = myvariable? myvariable.value : 'default';

console.log("The value of the variable is:" , myval);

Output

Handle null with the ternary operator

The value of the variable is: default

Lastly, we can save our web application from crashing by simply putting a try-and-catch block. Now let’s see an example in which we use try catch to handle a null value:

Code

console.log("Handle null with ternary operator");

let myvariable=null;

try

{

    let myval = myvariable.value;

}

catch(err){

  console.log(err.message);

}

Output

Handle null with ternary operator

Cannot read property 'value' of null

Solution 4: Check if The Object Is Null or Undefined

Make sure that the object you are trying to access is not null or undefined. If it is, you will get this error.

Solution 5: Check for Typo Errors

Make sure you have typed the object and property names correctly. A common mistake is spelling the object or property name incorrectly.

Solution 6: Check if the object and property exist

Make sure that the object and property you are trying to access actually exist. If you are trying to access an object or property that does not exist, you will get this error.

Solution 7: Use Type Checking

You can use type checking to ensure that the object is not null or undefined before trying to access its properties. For example, you can use the “typeof” operator to check the type of the object, like this:

if (typeof object !== "undefined" && object !== null) {
    // access object properties
}

Conclusion

In conclusion, TypeError: cannot read properties of null is a common error that occurs in JavaScript when you try to access a value of null or commit a spelling mistake.

This article shows how to fix JavaScript’s “TypeError: cannot read properties of null” error. We have discussed all the reasons and their solutions, so now you can eliminate erroneous lines in your code.

Let’s have a quick recap of the topics discussed above.

  1. What is a Null?
  2. What is DOM?
  3. Causes of TypeError: cannot read properties of null in JavaScript.
  4. How can we fix TypeError: cannot read properties of null in JavaScript?

Finally, you significantly understand the “TypeError: cannot read properties of null” error in JavaScript; it’s time to remember the concepts; comment below 👇 the most straightforward way of handling null value.

TypeError: Cannot read property ‘classList’ of Null in JavaScript is an error frequently happens to all programmers. Please refer to the document below to avoid making this mistake again.

Why does the error “TypeError: Cannot read property ‘classList’ of Null” in JS happen?

I have carefully observed and studied the error “TypeError: Cannot read property ‘classList’ of Null” in Javascript. It is an error that happens quite often to me. To describe it intuitively, you should look at the following example.

In index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="LearnShareIT">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id = "learn">Learn Share IT</title>
</head>
<body>

  <script src="main.js"></script>

</body>
</html>

In main.js file:

const text = document.createTextNode("LearnShareIT");
const add = document.getElementById("lear");
add.appendChild(text);

console.log(text);

First I create an element <title > with id="learn". Then in the main.js file, I wanted to call an element with that id, but I mistyped the id name. So my return value is null. If I stop here, the error won’t happen, but I used it to add the text "LearnShareIT". The null value could not add this text, giving an error.

Output

main.js:132 Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
    at main.js:132:5

To fix this error, please refer to some ways below.

How to fix this error?

Get the correct element

Make sure you get the element you want to get. If you can’t get the element, the result will return null, and when you manipulate that data, it will throw an error like this:

const text = document.getElementById("lear");

console.log(text);

Output

null

Please check the id name correctly:

const text = document.getElementById("learn");

console.log(text);

Output

<title id="learn">Title</title>

You can use this element to change the text content, and it will not raise an error:

const text = document.createTextNode("LearnShareIT");
const add = document.getElementById("learn");
add.appendChild(text);

console.log(text);

Output

LearnShareIT

The content of Title has been changed to LearnShareIT.

Put the main.js file in the correct location

Misplacing your js file can also affect the results. If the file is misplaced, it will not run and the return result will be null. It will repeat the above error if it is used to manipulate methods inside Javascript.

Make sure your file is located in the body tag as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="LearnShareIT">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id = "learn">Learn Share IT</title>
</head>
<body>

  <script src="main.js"></script>

</body>
</html>

Output

LearnShareIT

Summary

To avoid the error “TypeError: Cannot read property ‘classList’ of Null” in JS, make sure that the value you get is not null. The article showed two ways to handle it, let’s follow to solve your project.

Maybe you are interested:

  • TypeError: Cannot read property ‘top’ of Undefined in JS
  • TypeError: Cannot set properties of Undefined in JavaScript
  • TypeError: Converting circular structure to JSON in JS
  • TypeError: filter is not a function in JavaScript

Tom

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

Понравилась статья? Поделить с друзьями:
  • Cannot find appropriate setup exe file matlab ошибка
  • Cannot execute ошибка
  • Cannot establish connection with the update server ошибка
  • Cannot copy extracted data for ошибка cydia
  • Cannot communicate with server ошибка