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.
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.