Is there an issue with this straightforward Javascript function for switching the CSS class of an HTML body?

I have been diligently working on this piece of code for a while now. I have carefully placed alerts to debug it and ensured that the flow is correct. The necessary styles are all in place. Initially, the body starts with the "styleBlack" class. When the if statement condition is met, the body's class changes to "styleLight". However, despite meeting the else statement condition during a second call, the innerHTML of mDiv remains unchanged, as does the class of the body.

function ColorSwap() {
  var mDiv = document.getElementById("m_divSwap");
  if (mDiv.innerHTML = "Go Light") {
    mDiv.innerHTML = "Go Dark";
    document.body.className = "styleLight";
  } else {
    mDiv.innerHTML = "Go Light";
    document.body.className = "styleBlack";
  }
}

Answer №1

You should compare instead of assigning

Modification

if (mDiv.innerHTML = "Go Light")

replace with

if (mDiv.innerHTML === "Go Light")

Answer №2

Upon initial observation, it appears that within your conditionals, you may be mistakenly assigning a value instead of comparing two string values using the double equals operator.

Answer №3

In my opinion, utilizing the versatile JQuery framework can be beneficial as it is a reliable cross-browser standard JavaScript library. You can easily download it from the following link: (http://docs.jquery.com/Downloading_jQuery).

To enhance your webpage, consider adding an id attribute to the body element like so:

Here is an example of how you can implement the JQuery code:

function ColorSwap() {
  if ($("#m_divSwap").text() == "Go Light") 
  {
    $("#m_divSwap").text("Go Dark");
    $("#mybody").removeClass('styleBlack');
    $("#mybody").addClass('styleLight');

  }
  else 
  {
    $("#m_divSwap").text("Go Light");
    $("#mybody").removeClass('styleLight');
    $("#mybody").addClass('styleBlack ');    
  }
}

I hope this explanation proves helpful. Warm regards, Jose.

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

How to style Angular Material Dropdowns: Trimming the Left and Right Sides using CSS

Seeking to customize Angular Material Select to resemble a basic dropdown. Even after applying the disableOptionCentering, the dropdown list options still expand from the left and right sides (refer to Current picture below). The desired look would involve ...

Easily convert grams to kilograms with just a click of a button using JavaScript

Enter Grams(g): <input type="text" name="grams" id="grams"><br> <br> <button type="button" onclick="kiloConversion()">Convert to Kilogram</button> <p id="conversionResult"></p> ...

Encountering an Unexpected Token Error: Radium and React.js Inline Styles

Recently, I executed this command: npm install radium The installation was successful and I can confirm Radium is now present in my node modules folder. Reviewing my package.json file, I observed multiple dependencies including Radium. Could there be a ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

A function designed to detect errors based on the parameters supplied as arguments

In order to ensure secure access to my restful API, I am looking to implement an authentication function called "access". I would like the function to have the following structure whenever a user interacts with the server: access(id , token ,function(err) ...

What is the best way to retrieve the 'date,time' column from a MySQL database and use it as input for the google chart DateRangeFilter?

I am facing an issue with a column in my dataset that contains date-time values, such as '2017-2-2 10:30:20'. I need to use these rows as an input for a Date Range Filter in Google Chart. Can someone guide me on how to achieve this? I attempted ...

Having trouble loading a model with GLTFLoader in Vue2

I am utilizing GLTFLoader to import a model into my Vue2 application. My implementation follows the standard Three.js template. I directly copied the GLTFLoader code from the Three.js documentation. Despite creating a simple example, I am facing difficulti ...

HTML Form Validation - Conditional implementation based on radio button choice

My HTML form utilizes the JQuery Validate plugin to enforce mandatory fields. One of the form fields is a radio button with three options: Hours Days Unsure Another field requires the user to enter a number corresponding to their selection of "Hours" or ...

What are the best ways to stop jQuery events from propagating to ancestor elements?

I have a collection of nested UL's that follow this structure: <ul class="categorySelect" id=""> <li class="selected">Root<span class='catID'>1</span> <ul class="" id=""> <li>First Cat<span ...

Manipulating Vue.js data within HREF attributes using PHP

Does anyone know how to successfully pass the data from Vue into PHP? I've attempted a few methods, but when I try to use the resulting link in the href attribute (href = $ where $ name), it shows a strange string instead of the expected URL from the ...

Yeoman - A guide for integrating an express server task into Gruntfile.js from the generator-angular template

Currently, I am diving into the world of Grunt and attempting to integrate an Express server into my AngularJS application that was initially created with Yoeman. I've made adjustments to the following task as shown below: grunt.registerTask('s ...

What is the best way to send numerous forms to a PHP page when the quantity of forms produced varies randomly?

In my project, I have a code that dynamically populates input fields at the final step based on a user's selection. Each choice can have up to 6 input fields, resulting in a maximum of 4 forms or 24 input fields in total. For data persistence, I need ...

The tooltip callback in react-chartjs-2 is failing to function as expected

I've been utilizing the react-chartjs-2 library to create basic charts in my React project. In an attempt to customize the tooltip, I added a title: tooltips: { callbacks: { label: (tooltipItem, data) => { return tooltipItem?.valu ...

Error encountered: "XPathEvaluator is not defined" when using IEDriverServer and Internet Explorer with Selenium and Java in Microsoft Dynamics CRM

As part of my testing process for a CRM application with Selenium Java, I encountered an issue with a button that opens a new window. When executing the test, a Script Log Error appears in the new window stating, ReferenceError: 'XPathEvaluator&apo ...

React - what propType should be used for the Material UI icon?

I am planning to send a Material-UI icon to the Test component and I need to define the correct proptype for it. App.js import "./styles.css"; import VisibilityIcon from "@material-ui/icons/Visibility"; import Test from "./Test&q ...

Is it possible for a form to direct submissions to various pages depending on the value of certain fields

I need to set up a text field and submit button that will redirect users based on their input: index.html: If the user inputs "123" in the text box and clicks submit, they should be redirected to john.html page. AND If the user inputs "456" and clicks s ...

Verifying the type and quantity of an item

Looking at a piece of code where a specific condition is being checked, I'm curious to know why someone might want to skip this particular condition. var number = /^\d+/; var type = Object.prototype.toString.call(obj); for(var key i ...

Creating an object from select options in buildSelect methodWant to know how to convert

Based on the information from the http://www.trirand.com/jqgridwiki/doku.php?id=wiki:search_config, the value property can be defined as an object: If set as an object, it should be defined as a pair value:name - editoptions:{value:{1:'One',2:&a ...

In the template, I utilize both vue-router and jQuery. However, there seems to be an issue with $(document).ready() not functioning

Looking for guidance on using jQuery in Vue. I've noticed that when I refresh the page, $(document).ready() function is triggered. However, when I use vue-router to switch pages, $(document).ready() does not seem to work. <template> <div ...