I’m having an error Cannot read Property 'classList' of null at initialModal, but I don’t know how to resolve

Asked

Viewed 376 times

-1

The thing is, I’m a layman at programming, but I’m doing a website, and in this case, all you have to do is pop up, so you can book an appointment at a hair salon. I am following the following video tutorial: "https://www.youtube.com/watch?v=fu-enUG2VEE".

I’ve done the HTML and CSS part, defining the classes, id, and stylizations, but in this part of Javascript I’m having this error of Cannot read property 'classList' of null at iniciaModal

I followed the tutorial perfectly, of course respecting the way of my project, type, my CSS and Javascript are external HTML, all the files I use in the site project, are in the same folder and linked in HTML code.

I will briefly put the code part:

HTML

<head>
    <script type="text/javascript" src="index2.js"></script>
</head>
<body>
    <div id="modal-promocao" class="modal-container">
        <div class="modal">
            <button class="fechar">X</button>
            <h3>Solicitação de Agendamento</h3>
            <form>
                <input type="text" placeholder="Nome">
                <input type="text" placeholder="Número">
                <button>Manhã</button><button>Tarde</button>
                <input type="button" value="Enviar">
            </form>
        </div>
    </div>
</body>

Javascript

function iniciaModal(modalID) {
    const modal = document.getElementById(modalID);
    modal.classList.add('mostrar');
}

iniciaModal('modal-promocao');

If anyone can explain it to me in a simple way, because I’m not very familiar with all the codes. The goal is just to make this pop-up work properly and understand why this error of Cannot read property 'classList' of null at iniciaModal.

1 answer

2


Note that your script performs the function iniciaModal immediately (as soon as this part is evaluated).

Note also that you entered the <script> in the <head>, which shows that the script has been executed before the DOM is ready for manipulation (or even loaded).

That means when the Runtime of Javascript to execute the function iniciaModal, the ID element modal-promocao will not be "ready" for manipulation, which will make the function getElementById return null (since the element she sought "does not yet exist").

And as we already know, while trying to ignite a property of null (as you tried to do with classList), Javascript throws an error:

const elm = document.getElementById('eu-nao-existo');

console.log(elm); // null

// Lançará um erro:
// Uncaught TypeError: Cannot read property 'classList' of null
elm.classList;

To solve this, you need to ensure that the element you seek is "ready to be manipulated" when trying to get it using getElementById.

One option is to include the script before the closure of <body>, thus:

...
<body>
  ...

  <script type="text/javascript" src="index2.js"></script>
</body>

Thus you ensure that all HTML will have been properly loaded (and ready for manipulation) before the script be executed.

Another option is to just run the script before the issue of the event DOMContentLoaded, which also ensures the ability to manipulate the DOM. In this case, you do not need to change the structure of your HTML, just listen to the event. So:

function iniciaModal(modalID) {
  const modal = document.getElementById(modalID);
  modal.classList.add('mostrar');
}

document.addEventListener('DOMContentLoaded', function() {
  iniciaModal('modal-promocao');
});

Note that now the function iniciaModal will only be executed when the event DOMContentLoaded is fired.

  • I’m still very new in programming, so I didn’t understand very well what this DOM means a lot, but it depends on my studies, someday I learn straight, I put the script before closing the body and solved the problem, thanks for helping Luiz!

  • 1

    @Ramonrossini, this question may help you understand: What is DOM, Render Tree and Node?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.