Switch up your code and toggle a class on or off for all elements that share a specific class

I've been attempting to create a functionality where, upon clicking a switch, a specific class gets added to every element that is assigned the class "ChangeColors". Unfortunately, I have encountered some difficulties in achieving this task. The error message received reads:

TypeError: Cannot read property 'add' of undefined

CSS

.ChangeColors {
    background-color: #ff801b;
    color:black;
}

.bluecolor {
    background-color: blue;
    color:white;
}

Javascript

function ChangeColors() {
    var single = document.querySelector('.ChangeColors');
    var all = document.querySelectorAll('.ChangeColors');
    if (single.classList.contains('bluecolor')) {
        all.forEach(element => {
            element.classList.remove('bluecolor');
        });
        console.log("remove");
    } else {
        all.forEach(element => {
            element.classList.add('bluecolor');
        });
        console.log("add");
    }
}

Answer №1

Instead of trying to use .classList on a NodeList, which is the type returned by document.querySelectorAll, make sure to apply it to each individual element within the NodeList.

For a more efficient method, you can utilize classList.toggle to simplify the process without manually toggling each element.

const all = document.querySelectorAll('.ChangeColors');

all.forEach(elem => {
  elem.classList.toggle("bluecolor")
});

Answer №2

function AdjustShades() {
    var primary = document.querySelector('.AdjustShades');
    var allElements = [].slice.call(document.querySelectorAll('.AdjustShades')); // convert all items to array
    allElements.forEach(item => { // iterate through each item and apply condition
      if (primary.classList.contains('darkshade')) {
        item.classList.remove('darkshade');
        console.log("remove");
      } else {
        item.classList.add('darkshade');
        console.log("add");
      }
    })
}

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

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

JavaScript Asynchronous Functions Not Handling Await Calls Correctly

The two fadeInList functions control the fading animation of a continuous list split into two lines. The typeOutText function displays text and is supposed to execute List1 first, wait for it to finish, and then proceed with List2. However, after adding ke ...

How to Apply a CSS Class to the Body Tag in Angular 2.x

How can I add [class.fixed]="isFixed" to the body tag when Angular 2.x is bootstrapped inside the body (outside my-app)? <html> <head> </head> <body [class.fixed]="isFixed"> <my-app>Loading...</my-app> </body> & ...

Extract CSS from Chrome developer tools and convert it into a JavaScript object

Recently, we have started incorporating styles into our React components using the makeStyles hook from Material-UI. Instead of traditional CSS, we are now using JavaScript objects to define styles. An example of this is shown below: const useStyles = ma ...

I must click the web icon in order to open the link with buttons

I am having trouble with the buttons I added for my social media links. When I click on the button, it doesn't direct me to the link unless I click on the icon within the button. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7. ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an iss ...

Simplified user interface for detecting radio button clicks

Currently working on a form that includes radio buttons, where an update function is triggered whenever there is a user input change. The challenge I am facing is how to incorporate user-friendly radio buttons with a larger button area encompassing both t ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

Prevent the automatic inflation of bubbles on the D3 World Map

Currently, I am developing a D3 world map with a zoom feature that allows users to zoom in up to the boundary level of any country or county by clicking on it. I have successfully added bubbles that point to various counties in Kenya, and these bubbles en ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

Are You Able to Develop a Floating Window That Stays Persistent in JavaScript?

Looking to create a persistent floating window in a NextJS 14 app. This window needs to remain on top, even when navigating between browser windows. Want it to stay visible even when the browser window is minimized, like a Picture-In-Picture feature. Mos ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

The list of lists is giving an error: "Cannot read property 'name' of undefined."

What am I doing wrong here? let items = [{ name: 'client1' }, { name: 'client2' }, { name: "client3"}]; for (let i = 0; i < items.length; i++) { if (items[i]['name'].includes(self.autocomplete)) { self.box += '<l ...

Positioning a flex item to the right by using float

I am in need of assistance with my HTML layout. <div class="container"> <div class="sidebar" style="float:right"> Ignore sidebar? </div> <div> main content </div> </div> The container is set to have a flex disp ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Exploring the capabilities of using Next.js with grpc-node

I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application. Objective: I aim to create the client service once in the application and utilize it in getServerSideProps (wit ...

Looking to remove a row with php, html, and ajax?

Trying to remove a row from an HTML table has been my latest challenge while working with Materialize CSS. Here is what I have so far, where the ID corresponds to the employee ID: https://i.stack.imgur.com/rjwba.png Below is the code snippet: <?php ...