Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

311
Visualizações
Javascript check if color is white not working

Why is my code not working?

I want to check if the color of the paragraph is white(it is white because of the css) and when it is white i want to change it to black so it is visible

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

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The element does not have that property because it is defined in the css class. you need to define it inline or with javascript.

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

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

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't know the color at the time you test because the color is not inline. You need to check the computed style or just use a ternary

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

// the above is too complicated so why not just change to black if not black?
  
  lol.style.color = lol.style.color === "black" ? "white" : "black";
}
p {
  color: white;
}
<button onclick="myFunction()">Try it</button>

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

Better: Toggle the class

function myFunction() {
  const lol = document.getElementById("lol");
  
  console.log(lol.classList.contains("white")); // can be used or just toggle

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

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda