Transforming query language from jQuery to Pure JavaScript

I have the following jQuery code that I am attempting to remove and convert into standard JavaScript:

$('.switch').click(()=>{
    $([".light [class*='-light']", ".dark [class*='-dark']"]).each((i,ele)=>{
        $(ele).toggleClass('bg-light bg-dark')
        $(ele).toggleClass('text-light text-dark')
        $(ele).toggleClass('navbar-light navbar-dark')
    })
    $('body').toggleClass('light dark')
})

This is my updated version:

for (let s of [".light [class*='-light']", ".dark [class*='-dark']"]) {
  document.querySelectorAll(s).forEach((element, index) => {
    element.classList.toggle('bg-light bg-dark')
    element.classList.toggle('text-light text-dark')
    element.classList.toggle('navbar-light navbar-dark')
  })
}
document.querySelector("body").classList.toggle('light dark');

However, when I test this code, I get an error message:

Failed to execute 'toggle' on 'DOMTokenList': The token provided ('light dark') contains HTML space characters, which are not valid in tokens

If anyone can spot what's wrong with this or my revised code, I would greatly appreciate it. I'm new to Vanilla JS. Thank you!

Answer №1

It is due to the fact that the toggle function only accepts one class at a time:

['light', 'dark'].forEach(item => document.querySelector("body").classList.toggle(item));

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

IntersectionObserver activates prior to element's entrance into the viewport

I've set up a Vue component with the following structure: <template> <article> <!-- This content spans several viewport heights: you *have* to scroll to get to the bottom --> {{ content }} </article> <span ref ...

Utilizing babel-plugin-root-import in conjunction with babel 7

Recently, I decided to dive into setting up Babel 7 for the first time. It's been a bit of a learning curve as I navigate through unfamiliar territory. While I was able to successfully install and utilize @babel/plugin-proposal-optional-chaining, I&ap ...

Ionic 4's http.get.subscribe method fails to retain the retrieved value

I'm aware this might be a repeated question, but I haven't come across a straightforward answer yet, so here it goes. Below is the code snippet in question: fetchData() { let dataArray: Array<any> = [, , ,]; this.prepareDataReque ...

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

Yii CHtml::radioButton allows the addition of labels for each radio button option

My current code uses CHtml::radioButton, but I want to incorporate labels inline after each button for a better user experience. I attempted to use radioButtonList which allowed me to have labels, however, it did not allow the default 'no' optio ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Changing Observable to Promise in Angular 2

Q) What is the best way to convert an observable into a promise for easy handling with .then(...)? The code snippet below showcases my current method that I am looking to transform into a promise: this._APIService.getAssetTypes().subscribe( assetty ...

Transforming encoded information into a text format and then reversing the process

I am facing an issue with storing encrypted data in a string format. I have tried using the TextEncoder method but it seems to be creating strings with different bytes compared to the original ArrayBuffer. Here is the line causing the problem: const str ...

What is the best method to initialize a JavaScript function only once on a website that uses AJAX

Currently, I am facing an issue with a javascript function that needs to be contained within the content element rather than in the header. This is due to a dynamic ajax reload process which only refreshes the main content area and not the header section. ...

Halt the CSS transition on the preceding element

I tried to pause a CSS transition and came across a question with a solution that seems similar: Is there a way to pause CSS transition mid-way? However, I couldn't make it work for my code. I suspect the issue lies with the before element. What cou ...

The ExpressJS Req.method TypeError occurs when attempting to read the 'method' property of an undefined object

My node express server is throwing an error: Error in index.js. const bodyParser = require('body-parser'), express = require('express'), path = require('path'); const config = require('./config'); con ...

Combining JSON objects within an array

I'm working with a JSON Array that looks like this: [ {"Name" : "Arrow", "Year" : "2001" }, {"Name" : "Arrow", "Type" : "Action-Drama" }, { "Name" : "GOT", "Type" : "Action-Drama" } ] and I want to convert it to look like this: [ { "Name" : ...

How can I identify and remove duplicate elements from an array of objects?

elements= [ { "id": 0, "name": "name1", "age": 12, "city": "cityA" }, { "id": 1, "name": "name2", "age": 7, "city": "cityC" }, { &qu ...

Challenges with Webpack sourcemaps

As I delve into learning nodejs and react, my current challenge lies in building bundle.js and debugging it within the browser. However, despite creating the bundle.map file, I am faced with errors as the webpack tab fails to appear in the browser. DevTool ...

Adding to an existing array in MongoJS

I have been attempting to append data to an existing array in my mongoDB. The code snippet below is what I currently have, but unfortunately, it does not work as expected since all the existing data gets wiped out when I try to add new data: db.ca ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...

What steps are involved in integrating QuickBlox on your website?

I am completely new to web development and have a question about integrating QuickBlox into my website using JavaScript. I have included the necessary JavaScript files in my website and set up the QuickBlox admin application, but I'm not sure how to p ...

Transferring data using Ajax in a contact form PHP file

I recently started learning about AJAX and came across a code snippet online for sending data to a PHP file using AJAX. However, I'm facing an issue where I'm not sure if the data is being submitted or what is happening. The alert box doesn' ...

Unable to modify the Jest mock function's behavior

The issue I am facing involves the following steps: Setting up mocks in the beforeEach function Attempting to modify certain mock behaviors in specific tests where uniqueness is required Encountering difficulty in changing the values from the in ...