How to check the background-color of an element using jquery
Asked Answered
M

5

10
if($(this).css("background-color")==Crimson) 

is this correct ? .css("background-color","white") will change the color, but I don't want to change, I wanna know which color it is.

Mena answered 2/5, 2012 at 9:37 Comment(1)
The major browsers will always return the background color in rgb or rgba format older browsers will return the value which was set.Petulia
M
31

it works like this

if ($("#notify-9").css('background-color')=="rgb(220, 20, 60)") alert("matched");

you need to convert name to red, green, blue components, you might use this tool

http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php

Mythify answered 2/5, 2012 at 9:45 Comment(1)
Subtle detail... when writing rgb() take note of the leading spaces before the second and third value.Freightage
S
5

Use quotes "" or '':

if($(this).css("background-color")=="Crimson") 
Sladen answered 2/5, 2012 at 9:39 Comment(2)
Note that this will only work in older browser version. New Browsers will return "rgb(220, 20, 60)" if "Crimson" was set. Try it out: $("<div>").css("background-color","Crimson").appendTo("body").css("background-color")Petulia
@micha: Yeah if not set otherwise but background name shows op has set it.Sladen
P
1

Use quotes around the color name as:

if( $(this).css("background-color") == "Crimson" ) 

otherwise it is right.

Pontiac answered 2/5, 2012 at 9:39 Comment(0)
H
1

just use below line

if($(this).css("background-color")=="crimson") 

as css("background-color") attribute result will be in small letters . so if you will compare with capital obviously it will return false. :) Small trick hope that work

Herschel answered 8/11, 2013 at 12:9 Comment(0)
B
0

Possible answers in JavaScript is like this:

if(window.getComputedStyle(document.getElementById("notify-9"),null).getPropertyValue("background-color") == "rgb(220, 20, 60)"){
   alert("matched!");
}

// rgb(220, 20, 60) is equal to Crimson

Bloomfield answered 27/12, 2020 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.