Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda