How to troubleshoot Javascript code that fails to identify if a color is white

What could be causing my code to malfunction?

I am attempting to determine if the paragraph text color is white (as determined by CSS settings). If it is indeed white, I want to change it to black for better visibility.

function adjustColor() {
  if (document.getElementById("lol").style.color === "white") {
    document.getElementById("lol").style.color = "black";
  }
}
p {
  color: white;
}
<button onclick="adjustColor()">Modify Color</button>

<p id="lol">adadada</p>

Answer №1

The property is not included in the element because it is specified in the css class. It can be defined inline or with javascript instead.

function changeColor() {
  if (document.getElementById("lol").style.color === "white") {
    document.getElementById("lol").style.color = "black";
  }
}
p { /* this is unnecessary now */
  color: white;
}
<button onclick="changeColor()">Try it</button>

<p id="lol" style="color: white;">Sample text</p>

Answer №2

When conducting testing, the color may appear unknown since it is not defined inline. To confirm, you can utilize computed styles or opt for a ternary operator

function myFunction() {
  const lol = document.getElementById("lol");
  
  console.log(window.getComputedStyle(lol, null).color)

// Rather than complex logic, consider switching to black if it's not already black
  
  lol.style.color = lol.style.color === "black" ? "white" : "black";
}
p {
  color: white;
}
<button onclick="myFunction()">Try it</button>

<p id="lol">adadada</p></code></pre>
</div>
</div>
</p>
<p>An alternative and more efficient solution would be toggling the class</p>
<p><div>
<div>
<pre class="lang-js"><code>function myFunction() {
  const lol = document.getElementById("lol");
  
  console.log(lol.classList.contains("white")); // can be used or simply toggle

  lol.classList.toggle("white")
}
.white {
  color: white;
}
<button onclick="myFunction()">Try it</button>

<p id="lol" class="white">adadada</p></code></pre>
</div>
</div>
</p>
    </div></answer2>
<exanswer2><div class="answer" i="69392583" l="4.0" c="1632995602" m="1633007624" v="-1" a="bXBsdW5namFu" ai="295783">
<p>The exact color is uncertain during testing due to it not being directly specified. Validate by checking the computed style or employ a simple ternary operation</p>
<p><div>
<div>
<pre class="lang-js"><code>function myFunction() {
  const lol = document.getElementById("lol");
  
  console.log(window.getComputedStyle(lol, null).color)

// Simplify by changing to black when not already black
  
  lol.style.color = lol.style.color === "black" ? "white" : "black";
}
p {
  color: white;
}
<button onclick="myFunction()">Try it</button>

<p id="lol">adadada</p>

Optimal Method: Toggle the class

function myFunction() {
  const lol = document.getElementById("lol");
  
  console.log(lol.classList.contains("white")); // potential usage or direct toggle

  lol.classList.toggle("white")
}
.white {
  color: white;
}
<button onclick="myFunction()">Try it</button>

<p id="lol" class="white">adadada</p>

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

After clicking, I would like the text from the list item to have a style of "background-color: aqua" when displayed in the textarea

Is there a way to apply a highlight with a style of "background-color: aqua" in the textarea only to the word selected from the list above after clicking on it? See below for my HTML: <head> <script src="https://ajax.googleapis.com/ajax/libs/ ...

Encountering an Uncaught TypeError while trying to read properties of undefined (specifically 'remove') during a Change event is causing an issue for me

Looking to update the icons by changing the class from .fa-plus to .fa-minus for this specific menu section <div class="accordion-menu"> <h2 class="accordion-header" id="subseccOne"> ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

What steps can be taken to activate the remember password feature when using an AJAX login system?

I've developed a web application with a basic login box, utilizing jQuery AJAX for the login process. However, I'm facing an issue with prompting the browser to remember the password. How can I trigger the "Do you want the browser to remember th ...

Utilizing the modulo operation for organizing rows and columns

I’ve seen this question asked many times, but I’m still struggling to figure it out. The examples I’ve come across are either too complex or involve Angular or Javascript. My goal is to learn how to set up 4 columns within a row. // initiating a ...

When you click on the Admin Panel Side menu, the page refreshes instead of expanding the menu item

I have encountered a strange problem with the AdminLTE admin panel template that I am using in my Angular 11 application. Everything is loading fine with the menu items, but when I click on an item, instead of expanding the group, the page refreshes. Here ...

Using jQuery to assign a specific value to all select boxes

I am facing a challenge where I need to change the values of all select boxes on my page to a specific number. Here is the HTML structure: <select> <option value="-1" <option value="55">ENABLE</option> <option value= ...

Setting variables in AngularJS services without encountering JavaScript undefined errors

After developing an AngularJS module, I attempted to link a service and use it to share variables across the application. While most things are functioning properly, I encountered an issue when trying to set submenu[1] to an object. The error message sta ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

Issues with CSS functionality

Every now and then, this thing decides to work but most of the time it just doesn't. I have multiple tables in my application and the CSS is functioning properly for all of them. There's literally no difference with this one table, yet the CSS re ...

Deactivate Pagination with a Button-Based Approach

After conducting thorough research online, I have experimented with various approaches but unfortunately, none have proven successful. view image description here I am seeking guidance on how to disable pagination when clicking on the replace button. Due ...

AngularJS Form Validation Error Handling

I am in the process of implementing Form Validation using AngularJS, and I have come across a scenario involving ng-class that is confusing me. Could someone please explain why they are utilizing ng-class in this manner? The presence of a map and an arra ...

CSS HTML parent div cannot contain image properly

Creating a website using Bootstrap: <div class="row padding_zero"> <div class="col section px-0"> <img class="img-trans padding_zero" src="./svg/clouds-00.svg" style="margin-top: -150px& ...

Make a decision within Express.js to select the appropriate middleware modules based on specific conditions

In my express.js endpoint, I am dynamically selecting between middleware callbacks to execute: const middleware1 = require('./m1') const middleware2 = require('./m2') app.get('/call', async (req, res) => { if (req.code == ...

Is there a way to eliminate the surplus 2 download icons from this Angular code when there are a total of 3 users?

Here is some HTML code snippet: <tr *ngFor="let user of users"> <td> <h6 class="font-medium">{{user.id}}</h6> </td> <td> <h ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

Completing Forms Automatically with AngularJS

Hello! I'm just starting out with ng and I need to make an autocomplete textbox that will initiate an AJAX call when the text is changed. The catch is that the minimum length required to trigger the AJAX call is 3 characters. However, once the user en ...

Adding JavaScript to dynamically loaded AJAX content

I'm new to AJAX and JavaScript and unsure of how to get it working. Here is the website: When you click on portfolio images, the details load via AJAX. I want to create a slideshow for projects with multiple full-sized images. However, due to the co ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

javascript triggering before its designated event happens

I've encountered a puzzling issue with a complex file where a javascript function is behaving unexpectedly—it seems to be firing before its designated event actually takes place. I have ruled out the possibility of an onload event triggering this be ...