3

Why won't this work?

Browser = Safari

<p style="color:blue;">foo</p>

if ($("p").css(("color") === "blue")) {
        alert(1);
}

Thank you

0

4 Answers 4

8

It's all about syntax and brackets:

if ($("p").css("color") === "blue") {
        alert(1);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I feel very dumb!
4

Initially, the bracket placement is wrong. You should be getting the value of the CSS property "color" with .css("color") and testing for equality with your value like so:

if ($('p').css('color') === 'blue') {
    alert('color is blue');
}

However, some browsers will return the rgb value instead which will not match your "blue", for example Chrome and Firefox return rgb(0, 0, 255) for $('p').css('color'), so you might want to test against the rgb (or even hex - '#0000ff') value as well. All the values are logically but not textually the same.

var color = $('p').css('color')
if (color === 'blue' || color === 'rgb(0, 0, 255)' || color === '#0000ff') {
    alert('color is blue');
}

Taking it even further, the if condition should probably take into account the case of the color. 'BLUE' or '#0000FF' are also valid.

Comments

0

i think it should be : if ($("p").css("color") === "blue"){ alert(1); }

Comments

0

At least in Firefox and Chrome

$("p").css("color") 

returns rgb(0,0,255) so your condition will not be true anyway. So maybe such workaround:

if ($("p").attr("style").contains('color:blue;')) {
    alert(1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.