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

Employ node's gm library in combination with promises and buffers

Using gm with Bluebird has been a bit tricky for me. Initially, I tried this approach: var gm = require('gm'); var bluebird = require('bluebird'); gm = bluebird.promisifyAll(gm); However, when attempting to execute the following code: ...

Steps for triggering Docusign Clickwrap with a button press

My current project involves integrating docusign clickwrap codes. I want the clickwrap to appear when a user clicks a button. However, when I use the code below, the clickwrap opens directly. How can I trigger the ds-click using a button click event? For ...

Execute AngularJS $q.all, regardless of any errors that may occur

Is there a way to ensure $q.all is triggered even if the promises return errors? I'm working on a project where I need to make multiple $http.post requests, sending user-inputted values from text fields. The backend (Django REST framework) has a valu ...

Utilizing the .finally method on a promise that is already being handled with try/catch statements elsewhere may lead to an UnhandledPromiseRejection

Recently, I've come across an unexpected behavior while working with nodejs. To illustrate this strange occurrence, let's consider the following example: Imagine we have two functions, foo and bar. The foo function creates a promise, attaches a ...

Leverage the package.json script without relying on any yarn/npm commands

Can scripts commands be executed within the package.json file without needing to include yarn or npm? For example: "scripts": { "get": "node index.js" } Currently, in order to run this script I have to use yarn get [ar ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Error: The Object #<Object> does not contain a function named 'Schema'

Below is the user model schema that we are using. However, when I try to run it on my localhost, I encounter an error: TypeError: Object # has no method 'Schema' // app/models/user.js // Required modules var neo4j = require('neo4j'); ...

Gain command over the underline style of text without relying on the border property

Ingredients: just a simple text input field. Question: Is there a way to customize the size, color, and position of the underline styling on an input tag? I noticed that the property text-decoration-color is supported in the moz browser engine, but I&apos ...

After clicking a button in AngularJS, how can you retrieve one of the two JSON files and store it in a $scope variable?

For instance, You have two JSON files: Json file #1: [{colorname:blue},{colorname:blue}] Json file #2: [{colorname:red},{colorname:red}] Within the controller, there exists a variable called $scope.color In the HTML code, there are two buttons named " ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

Display the keys of a nested array in Vue.js when the structure is unknown

Here is a representation of a dynamic array I have: nodes: [ { n1: "Foods", }, { n4: "Drinks", b7: [ { a2: "Beers", a4: [ ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

encountering an issue with the react hook useHistory leading to an error

I recently encountered an issue while implementing useHistory() in my code. Previously, I had used it without any errors, but now I'm getting the following error in this component: Line 6:18: React Hook "useHistory" is called in function "showPost" ...

Steps to seamlessly integrate puppeteer with an active Chrome instance or tab

Is there a way to connect puppeteer to an already open Chrome browser and control a specific tab? I believe it may involve starting Chrome with the --no-sandbox flag, but I am unsure of the next steps. Any assistance on this matter would be greatly apprec ...

Exploring the Power of D3.js: Loading and Visualizing Multiple Networks using JSON Files and the Force

I have a collection of networks consisting of nodes and links stored in various JSON files. I am using D3.js to load them into a Force Layout, where they each load and layout perfectly when loaded individually. However, I would like to enhance the function ...