Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hidayat3676's avatar

how to compare two colors value in jquery

i have the following coded


$(document).ready(function () {
$('.like-icon-btn').click(function () {
var postIdLiked  = $(this).data('id');
var userIdLiked  = $('.likesUserId').val();
var color        = $(this).css('color');
var id           = $(this).attr('id','rand_'+Math.random());
    //$(this).css('color','red');

        console.log(color);
    if(color === 'rgb(255,0,0)'  ){
              $(this).css('color','red');

    }

in console i am getting value  of color is rgb(255,0,0)

in this code the if condition is not executing what am i doing wrong in this

0 likes
4 replies
Cronix's avatar

Nothing, that's how css translates color behind the scenes in browsers. "red" = rgb(255,0,0). 255 for red (full red), 0 green and 0 blue.

Browsers just are able to use named colors as a convenience, but internally they translate them to their own rgb counterpart because everything is a rgb color. They may differ from browser to browser as well. They probably wouldn't change for "red", "blue", "green", "black" or "white", but anything else like "cyan" may not be the same in Firefox as it is in chrome. So it will always return the rgb value, not the "named" value.

hidayat3676's avatar

please look into my code i am comparing with actual rgb value not with name value

Cronix's avatar

Are you sure you get rgb(255,0,0) and not rgb(255, 0, 0) with spaces after the commas?

<div id="mydiv" style="color:red">Test div</div>

<script>
let color = $('#mydiv').css('color');

if (color === 'rgb(255,0,0)') {
    console.log("found "+color+" with no spaces");
}
if (color === 'rgb(255, 0, 0)') {
    console.log("found "+color+" WITH spaces");
}
</script>

shows "found rgb(255, 0, 0) WITH spaces"

Please or to participate in this conversation.