Problem encountered with modal and JavaScript: Uncaught TypeError: Unable to retrieve the property 'classList' of null

Trying to implement a modal feature for the first time but encountering an error when clicking the button. Unsure if I'm following the correct procedure as a JS beginner. Any assistance would be appreciated.

ERROR { "message": "Uncaught TypeError: Cannot read property 'classList' of null", "filename": "https://stacksnippets.net/js", "lineno": 67, "colno": 21 }

const open = document.getElementById('open');
const modal_container = document.getElementById('modal_container');
const close = document.getElementById('close');

open.addEventListener('click', () => {
    modal_container.classList.add('show');
});

close.addEventListener('click', () => {
    modal_container.classList.remove('show');
});
button {
  background-color: crimson;
  border: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  color: white;
  padding: 20px 30px;
  font-size: 14px;
  border-radius: 5px;
  margin-top: 10px;
}
.modal-container {
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  opacity: 0;
  pointer-events: none;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  z-index: 1;
}
.modal-container .show {
  pointer-events: auto;
  opacity: 1;
}
.modal {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  background-color: white;
  border-radius: 5px;
  padding: 30px 50px;
  width: 800px;
  max-width: 100%;
  text-align: center;
}
.modal h1 {
  margin: 0;
}
.modal p {
  opacity: 0.7;
  font-size: 14px;
}
 <button id="open">Introduction</button>
  <div class="modal-container" id="modal-container">
      <div class="modal">
          <h1>Introduction</h1>
          <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta pariatur ut, veniam illum nemo repellat explicabo dignissimos ex ipsum aliquid.</p>
          <button id="close">Click here to close.</button>
      </div>
  </div>
  

Answer №1

Remember, your identifier is modal-container and not modal_container

const modal_container = document.getElementById('modal-container');

UPDATE: Double check your CSS selector to ensure it is accurate; there should be no space if the classes belong to the same element and not its children.

.modal-container.show

Answer №2

There appears to be a small mistake in your code.

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

Update to:

const modal_container = document.getElementById('modal-container');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method to remove a buffer in threejs in order to minimize GPU memory leakage?

I am facing an issue with a large mesh containing over 5 million triangles. I utilized BufferGeometry with attributes such as position, color, normal, and index. However, there comes a point where I need to remove certain indices from the index attribute. ...

Designing table rows to resemble full-width cards

Looking for a way to transform the rows of a table into full-width cards while maintaining the row layout? Here's what I have tried so far: tbody>tr { display: block; padding: 1rem 0.5rem 1rem 0.5rem; margin: 1.5rem; border: 1px solid rgba( ...

Tips for applying CSS to background images

Just working with one div here <div id="particles-js" > and in my CSS, I've got this: #particles-js{ width: 100%; height: 100%; background-color: #b61924; background-image: url("../js/image.jpg"); background-size: cover; backg ...

What is the best way to position a bigger character directly above a smaller container?

My goal is to center a single character, using CSS, in a span that is smaller than the character itself. The setup I have is: <span id="A">X</span><span id="B">Y</span><span id="C">Z</span> All three spans are styled ...

Ways to dynamically assign value to a checkbox using jquery

var sites = sites_str.split(","); $.each(sites,function(i,j) { $('.check').append("<input type=checkbox name=site_name value=sites[i]>"+sites[i] +"</br>" }) I am facing an issue when trying to retrieve the values of selected check ...

What is the best way to incorporate additional features into the HTML content that I display using Express?

Currently, I am working on a project using NodeJS and express in order to capture data from a form and save it to a local file on my computer. Since I am developing locally (localhost), the local file is located on my server. While I have successfully rend ...

Creating interactive carousel slides effortlessly with the power of Angular and the ngu-carousel module

I'm currently tackling the task of developing a carousel with the ngu-carousel Angular module, available at this link. However, I'm facing some challenges in configuring it to dynamically generate slides from an array of objects. From what I&apos ...

Retrieve the identifiers of various HTML elements and store them in an array

Within a div, there are multiple objects. I am trying to retrieve the IDs of all elements based on their class, knowing that the number of elements may vary. So far, my attempt has been: arr = $(".listitem #checkBox").hasClass('checkedItem').att ...

What is the best way to horizontally align a group of list elements while also displaying them side by side?

I've been working on creating a Sign Up page and here is the code I have so far: <div class="form"> <ul class="tab-group"> <li class="tabsignup"><a href="/signup.html">Sign Up</a ...

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

Managing checkboxes using node.js and mongoose

This particular ejs file showcases a form featuring multiple checkbox inputs generated by looping through a database. Upon submission, a post request is triggered, and this request is subsequently managed by the app.post <form action="/" m ...

Devbridge AutoComplete leveraging Ajax fails to populate suggested options

Currently, I have an autocomplete field that triggers a server search based on the fullname in a database, with the response being in JSON format. The issue arises when using the JSON server response instead of a local array, as the suggestion list does n ...

Is there a way to keep Angular from automatically re-sorting my list when I make edits to it?

I have designed a small application with Angular for managing Todolists. Each list contains multiple todos, where each todo has attributes such as name, value1, and value2. To automatically sort each list using Angular, I utilized ng-repeat="todo in selec ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...

The user's input is not being bound properly when using $scope.$watch

Just started my Angular journey and I've been stuck for the past couple of days trying to figure out how to bind data from a new search using a service. Previously, I had the search functionality working with the code below before transitioning to a s ...

jQuery live DataAttribute manipulation

Here is the code snippet I am working with: <head runat="server"> <title>Sidebar</title> <link href="css/style.css" rel="stylesheet" /> <script src="scripts/jquery-1.11.1.min.js"></script> <script src ...

Resolving Uncaught TypeError in React when trying to read properties of undefined (specifically 'map')

As a newcomer to React and API usage, I am facing difficulty resolving the error below. My goal is to showcase a carousel of images using React.js but encountered this issue: Error message: Popular.jsx:26 Uncaught TypeError: Cannot read properties of unde ...

Node-RED experiences crashes while attempting to make HTTP requests to access a web service

I'm currently facing a challenge in creating a node that can make web service calls. The tools I'm using are: Node-RED version: v0.17.5 Node.js version: v8.4.0 An exception is being thrown, and here's the error message: node-red_1 ...

Using React-router for server-side rendering and loading data with ajax calls

Currently I am working on implementing react-router in my project, but I seem to be facing some major concept misunderstandings. There are certain components in my application that require fetching data from the server. Previously, I used the following cod ...