Unable to delete body class that was previously added through a click event

I seem to have hit a roadblock, likely related to the use of bind, however, I can't pinpoint the issue. I am able to add a class to a body tag, but struggling to remove it later on.

const add_body_class = document.querySelectorAll('.btn-add-class');

add_body_class.forEach(item => {
  item.addEventListener('click', event => {
     document.body.classList.add('foobar');
  })
});

const remove_body_class = document.querySelectorAll('.btn-remove-class');

remove_body_class.forEach(item => {
  item.addEventListener('click', event => {
     // this doesn't work
     document.body.classList.remove('foobar');
     // click event works
     console.log("clicked");
  })
});

By the way, I need to utilize multiple selectors and document.querySelectorAll due to having multiple instances in the code that cannot be modified.

Any assistance would be greatly appreciated!

Answer №1

My solution was successful by enclosing it within a DOMContentLoaded listener.

<!DOCTYPE html>
<html>

<body>
<button class="btn-add-class">Add</button>
<button class="btn-add-class">Add</button>
<button class="btn-add-class">Add</button>
<hr>
<button class="btn-remove-class">Remove</button>
<button class="btn-remove-class">Remove</button>
<button class="btn-remove-class">Remove</button>
</body>
<style>
.foobar{
  background-color: yellow;
  }
</style>
<script>
document.addEventListener("DOMContentLoaded", () => {
const add_body_class = document.querySelectorAll('.btn-add-class');

add_body_class.forEach(item => {
  item.addEventListener('click', event => {
     document.body.classList.add('foobar');
     console.log("added");
  })
});

const remove_body_class = document.querySelectorAll('.btn-remove-class');

remove_body_class.forEach(item => {
  item.addEventListener('click', event => {
     // this doesn't work
     document.body.classList.remove('foobar');
     // click event works
     console.log("removed");
  })
});
})
</script>

</html>

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

"Implementing a function in JavaScript to automatically pause other audio sources when a new one begins playing

On my html5 page, I have more than 5 audio players using the audioplayer.js script. Is there a simple JavaScript code that can pause all other players when one player is currently playing? Here is an example using jQuery: $( function(){ $("audio").au ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

Error in the HTML DOCTYPE declaration affecting JavaScript files

My login page is displaying 5 errors, specifically a syntax error SyntaxError: syntax error <!DOCTYPE html> on 5 JavaScript files. After investigating, I discovered that these files are located in a non-public directory. Is there a way to exclude th ...

What are the steps to incorporate a jquery-ui checkbox into a widget?

I have encountered an issue where using a jquery-ui checkbox within a container that has the class ui-widget-content is causing a problem with the CSS rules. Specifically, the ".ui-widget-content .ui-state-hover" rule is overriding the .ui-icon-check rule, ...

Capture latitude and longitude using HTML5 Geolocation and store the values in a PHP variable

In the midst of a project, I am tasked with obtaining the longitude and latitude of a user in order to pinpoint their location. The challenge lies in storing this data in PHP variables, which will ultimately be saved in a MySQL database. Can anyone offer ...

I have not made any changes to the <div> tag with my CSS or JavaScript coding

Click here to see the problem I am facing on JSFiddle. I am trying to create a loading screen that will slide up after a few seconds using jQuery. Although I am familiar with HTML, JavaScript, and CSS, I am still new to jQuery. I have a feeling that the so ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

Tips for disregarding global CSS in Nuxt.js?

I've been utilizing a boilerplate that integrates with the CoreUI template from GitHub, and it's been working well. However, I am now looking to customize my index page with a unique style, and I'm encountering issues where the global CSS fr ...

Attention: Issue with 'className did not match' error in react-material-ui-carousel

I am currently utilizing React, NextJS, and Material UI in my project I recently integrated the react-material-ui-carousel package, but encountered the following error: Warning: Prop className did not match. Server: "MuiButtonBase-root MuiIconButton ...

Exploring arrays to find the maximum sum of elements

Struggling to develop a Javascript function that identifies which element in an array of numbers (specifically phone numbers) has the highest sum? Despite feeling frustrated and defeated, I believe I am on the right track. Could someone provide some guidan ...

Algorithm-driven dot selector

We are currently utilizing ReactJS and MaterialUI for our frontend development. We are facing a challenge with a specific component, unsure of whether it should be a slider (https://material-ui.com/components/slider/), stepper (https://material-ui.com/comp ...

Is there a way to determine if a Dojo dialog has been successfully loaded on the page?

I have a function that needs to close a Dojo dialog if it is currently open. How can I determine if a dojo dialog is active? Should I rely on pure JavaScript and check for its existence by ID? if (dijit.byId("blah") !== undefined) { destroyRecursive ...

Having an issue with the Show/Hide Javascript toggle on the same page. Multiple hidden texts are appearing simultaneously. Seeking a solution without the use of JQuery

This code is functioning efficiently. I am looking for a way to display and conceal various texts using different expand/hide links within multiple tables on the same page. I prefer to achieve this without using JQuery, just like in this straightforward sc ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

The beauty of Angular.js filters lies in their ability to create nested

I'm currently working on developing a straightforward pagination filter for Angular, which can be implemented as shown below: <ul> <li ng-repeat="page in items | paginate: 10"> <ul> <li ng-repeat="item in p ...

Corrupted image retrieved from a MySQL database stored as a Longblob data type

I've noticed many similar questions with different code solutions, but I've encountered a problem where changing the datatype to "Longblob" did not fix the issue. Even though my datatype is already Longblob, I still have broken images. My $pid i ...

"Enhancing website performance with JavaScript by leveraging DOM innerHTML scrollHeight

Here is a two-part question I have: The first part of the question: test A: t1 = new Date().getTime(); for (i=0; i<205; i++) { document.getElementById("divTest").innerHTML = sText; } t2 = new Date().getTime(); ...

"Adjust the placement of a personalized marker on a Google Map using google-map-react

I have incorporated google-map-react into my React project and I have designed custom markers. The markers are displayed at the correct location but from the top left corner: https://i.sstatic.net/e6lGN.png The red dot indicates the exact location. Howe ...

With NodeJs, Mongoose refrains from storing any data in the database

Recently, I encountered a puzzling issue with my code designed to store superhero names and powers in a database. Despite all the connections functioning correctly, I faced an unexpected challenge. When running mongod, I utilized the --dbpath C:/nodeproje ...

What steps do I need to take to incorporate Material UI icons into my REACT project?

After reviewing the documentation, I found it somewhat confusing with terms such as "MaterialIcon, SVGIcons, Icons". If you are interested, you can check out the link here. I am looking for a simple explanation of the process from installation to using th ...