search

Home  >  Q&A  >  body text

How to stop Javascript code from automatically converting hsl to rgb

I have this code where I assign a color to an object and then use a condition to check if the item has been selected. However, the condition doesn't work because javascript (or the browser) converts hsl to rgb, which prevents any matching from happening. I'm wondering if there is a way to prevent this behavior in JS (or browsers), and if not, why does it happen?

function selecionarNota() {

    if (this.style.backgroundColor == 'hsl(25, 97%, 53%)') { 
        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

    } else {

        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

        this.style.backgroundColor = 'hsl(25, 97%, 53%)';
        this.style.color = 'white';

    }
}

I did realize that I could solve this problem by using rgb in my code. But I'd really like to understand why this happens.

P粉806834059P粉806834059232 days ago429

reply all(1)I'll reply

  • P粉076987386

    P粉0769873862024-04-01 10:48:37

    This happens because it is a browser standard.

    I recommend creating css classes with these colors and applying these classes in javascript. You can then use element.classList.contains(class) in your condition.

    reply
    0
  • Cancelreply