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

206
Visualizações
How can i make JavaScript If Style Color work?

I have a simple if condition that checks the color of a element...

function changeBackgroundColor(element) {
          if (element.target.style.color == "#1abc9c"){
            // Do nothing
          } 
          else { // Whatever }

But it is not working. If i use common names like "Yellow, green, etc" it works. Any tips?

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

0

style.color gives the direct color name or rgb value. It does not gives hex code. So for your case, you first need to change your hex code to rgb, then compare it with style.color So what you can do you can create a utility function

function getRgbFromHex(hexColorCode){
  const hexCode =  hexColorCode.startsWith('#') ? hexColorCode.substr(1) : hexColorCode;
  const hexR = hexCode.substring(0,2);
  const hexG = hexCode.substring(2,4);
  const hexB = hexCode.substring(4,6);
  
  return `rgb(${parseInt(hexR, 16)},${parseInt(hexG, 16)},${parseInt(hexB, 16)})`
  }

and then you can change your if condition to UPDATE Removing spaces from style.color

if (element.target.style.color.replace(/\s/g,'') == getRgbFromHex("#1abc9c"))
about 4 years ago · Juan Pablo Isaza Relatório

0

document.getElementById('main').style.color returns a RGB value, not a HEX value.

Example:

if (document.getElementById('main').style.color == 'rgb(26, 188, 156)') {
    console.log("Colour is set")
} else {
    
}
<div id="main"  style="color: #1abc9c">
    Hello, world!
</div>

<script src="test.js"></script>
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