The occurrence of Multiple Button events leads to an error message stating: "Uncaught TypeError: Cannot read property 'remove' of undefined"

I am struggling to add an EventListener to each Delete Button (1,2,3) as I keep encountering an error that says "add" is undefined. Do you have any suggestions on how to fix this issue? My goal is to display a confirmation window when the DELETE button is clicked

index.html

<div id="confirmWindow" class=" hidden">
    <p>Are you sure want to delete?</p>
    <button class="buttonYes">Yes</button>
    <button class="buttonNo">No</button>
</div>
<button class="" id="trashIcon">Delete 1</button>

<div id="confirmWindow" class=" hidden">
    <p>Are you sure want to delete?</p>
    <button class="buttonYes">Yes</button>
    <button class="buttonNo">No</button>
</div>
<button class="" id="trashIcon">Delete 2</button>

<div id="confirmWindow" class=" hidden">
    <p>Are you sure want to delete?</p>
    <button class="buttonYes">Yes</button>
    <button class="buttonNo">No</button>
</div>
<button class="" id="trashIcon">Delete 3</button>

app.js

const deleteButton = document.querySelectorAll('#trashIcon');
const confirmWindow = document.querySelectorAll('#confirmWindow');
const buttonYes = document.querySelectorAll('.buttonYes');
const buttonNo = document.querySelectorAll('.buttonNo');


const openWindow = function (){
  confirmWindow.classList.remove('hidden');
  deleteButton.classList.add('hidden');
}

const closeDeleteWindow = function (){
  confirmWindow.classList.add('hidden');
  deleteButton.classList.remove('hidden');
}

for (let i=0; i < deleteButton.length; i++){
  deleteButton[i].addEventListener('click', openWindow);
}

for (let i=0; i < buttonNo.length; i++){
  buttonNo[i].addEventListener('click', closeDeleteWindow);
}

Answer №1

Ensure that IDs are unique for HTML elements. Use classes instead of IDs for better organization and flexibility.

<style>.hidden {display: none;}</style>
<div id="confirmWindow1" class="confirmWindow1 hidden">
    <p>Are you sure want to delete?</p>
    <button class="buttonYes">Yes</button>
    <button id="buttonNo1" class="buttonNo">No</button>
</div>
<button class="trashIcon" id="trashIcon1">Delete 1</button>

<div id="confirmWindow2" class="confirmWindow2 hidden">
    <p>Are you sure want to delete?</p>
    <button class="buttonYes">Yes</button>
    <button id="buttonNo2" class="buttonNo">No</button>
</div>
<button class="trashIcon" id="trashIcon2">Delete 2</button>

<div id="confirmWindow3" class="confirmWindow3 hidden">
    <p>Are you sure want to delete?</p>
    <button class="buttonYes">Yes</button>
    <button id="buttonNo3" class="buttonNo">No</button>
</div>
<button class="trashIcon" id="trashIcon3">Delete 3</button>




const deleteButton = document.querySelectorAll('.trashIcon');
const confirmWindow = document.querySelectorAll('.confirmWindow');
const buttonYes = document.querySelectorAll('.buttonYes');
const buttonNo = document.querySelectorAll('.buttonNo');


const openWindow = function (obj){
  document.querySelectorAll('.confirmWindow'+obj.id.replace('trashIcon',''))[0].classList.remove('hidden');
  obj.classList.add('hidden');
}

const closeDeleteWindow = function (obj){
  document.querySelectorAll('.confirmWindow'+obj.id.replace('buttonNo',''))[0].classList.add('hidden');
  document.querySelectorAll('#trashIcon'+obj.id.replace('buttonNo',''))[0].classList.remove('hidden');
}

for (let i=0; i < deleteButton.length; i++){
  deleteButton[i].addEventListener('click', function(){
    openWindow(this);
  });
}

for (let i=0; i < buttonNo.length; i++){
  buttonNo[i].addEventListener('click', function(){
    closeDeleteWindow(this);
  });
}

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

Animating scrollTop using JQuery

There are two buttons with hidden parts related to each. When a button is clicked, its associated part will be displayed and the document will scroll to the top. Issue: The displayed part does not move to the top as intended. Your assistance in resolving ...

"Selecting elements with CSS using the 'element'

While exploring some websites for studying purposes, I came across this code snippet. .site-header .widget-area span.but As a beginner in CSS, I'm curious to know more about the span.but part. Is it similar to the :not pseudo selector? ...

Employing both Angular 1 and Angular 2 in conjunction

As a newcomer to angular, this is my first experience. My ultimate goal is to incorporate the following component into Angular 2: While I have some knowledge of JavaScript, I am attempting to integrate an Angular 1 library into an Angular 2 project. Aft ...

Reply in Loopback on remote method beforeRemote hook is to be sent

In my application, I am utilizing loopback v3. The specific use case I am tackling involves validating the presence of a token in the request header. If the token is invalid, I need to send an appropriate message in a standardized format. My approach has b ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Sending multiple HTTP requests sequentially

I've been attempting to send a request object to a server repeatedly in a loop, aiming to execute the task 1000 times. The scenario is reminiscent of the movie Office Space, where a small sum is extracted from numerous bank accounts. Here's the ...

Angular: Selecting all checkboxes outside of an ng-repeat loop

Project Overview In my project, there is a system for managing small product orders. Users have the ability to add order lines and attach one or more products to each order line. While it may be uncommon to have multiple products on the same order line, t ...

Issue encountered with Ionic and Angular 2: Denied application of style from 'http://localhost:8100/build/main.css' due to unsupported MIME type ('text/html')

Initially, everything was going smoothly with my Ionic build, but things took a turn when I tried to test it on my iPhone. After stopping the server and running ionic serve --address localhost, I noticed that my stylesheet wasn't loading. Even after r ...

What is the best way to cluster related data points and display them together?

In order to efficiently manage the data I receive, it is necessary to group it based on specific criteria and display these groups in the user interface. "ServiceRequest": [ {"Status": "Re-Open", },{ "Status": "Open", ...

Conceal the slider thumb within the material-ui framework

I've been attempting to conceal the slide thumb, initially without using a library. However, I started considering utilizing material-ui as it might make the process easier. Hence, I'm seeking assistance here. Below is my code snippet: import * ...

The visual content I have does not fill up the entire screen, which results in some empty spaces in the layout

Whenever I insert an image, I strive to have it fill the entire space but end up with white gaps. This is my code: <div style="background-image: url('../assets/img/food-with-ingredients.jpg'); -webkit-background-size: cover; -moz-back ...

Node.js equivalent of PHP's SimpleXMLParser

One of the most user-friendly XML reading and writing APIs I've come across is PHP's SimpleXMLElement. For instance, to generate a DOM for the following XML code: <root> <foo> <bar baz="goo"> moo ...

What is the reason for the initial DOM operation taking significantly longer than subsequent ones?

Why is the first operation much more despite the subsequent manipulation of the DOM being practically identical in time when both are written with the realization in JS and jQuery? Link to Javascript source // ES5 // Sending a message function sendMessa ...

Troubleshooting border-left and td alignment problems in an HTML email displayed in Outlook 2013

Currently, I am facing a frustrating challenge while working on an HTML email signature. It seems to display perfectly in all email clients except for Outlook 2007, 2010, and 2013. The specific issue I'm encountering is with the alignment of the secon ...

Check out the new Bootstrap 5 form when it's successfully validated

I need to execute some JavaScript if my form is valid. I am using Bootstrap 5 and found this code, but I am unsure how to add 'if form.is_valid {}' <script> (function () { 'use strict' const forms = document.querySelectorAll(&apos ...

IntelliJ automation in Java does not allow clicking the button

Currently, I am on the PayPal page and I need to automate clicking the agree button. <form id="ryiForm" class="proceed ng-pristine ng-valid" ng-class="{true: 'validated'}[validated]" ng-submit="confirm.$valid && onPay()" novalidate= ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

Issue with Jquery plugin malfunctioning on dynamically loaded elements via Ajax requests

Description: I'm currently working on a project where I need to load elements with expiration dates pulled from my database. To achieve this, I am using a Jquery plugin that relies on the HTML5 Data Type Attribute for setting the "end date". Everythin ...

A guide to examining pixels in Three.js

I have a query about comparing two textures at a pixel level in three.js. I am unsure of how to achieve this as the documentation for Three.js does not provide clear answers, with some classes remaining undocumented. In summary, I am looking to determine ...

Retrieve information following an Ajax call inside a pre-designed template

Upon rendering a page with data put together by EJS, the goal is to refresh a section (thirdRow) of the page whenever the user submits new data. The refreshed section should display both the newly submitted data and the existing data. Although I have obtai ...