Ron Ron - 4 months ago 11
CSS Question

Testing CSS color with JavaScript

This is a simple HTML/JavaScript file:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<title>Javascript</title>
<script type="text/javascript" src="jquery.min.js"></script>
<style>
.red {
color:rgb(255,0,0);
}
</style>
</head>
<body>
<p class="red">The quick brown fox jumped over the lazy developer.</p>

<script type="text/javascript">
$("p").each (function (index,element) {
var color = $(element).css("color");
alert("color=" + color); //the alert says color=rgb(255,0,0)
if (color==rgb(255,0,0)) {
alert("color is rgb(255,0,0)");
//this alert never fires and the code never gets here.
$(element).css("color","#000000");
$(element).css("background-color","#ffff00");
}
});
</script>
</body>
</html>


Why does the test
if (color==rgb(255,0,0)
fail? Isn't the color
rgb(255,0,0)
? Does seem to matter if the test says
color="red"
, either.

Answer

The call to .css("color") returns a string, so you have to compare it to a string. Also, since you are doing a string comparison, whitespace is important: rgb(255,0,0) !== rgb(255, 0, 0).

This works just fine:

$('document').ready(function() {

  $("p").each(function(index, element) {
    var color = $(element).css("color");
    alert('color=' + color);
    if (color == 'rgb(255, 0, 0)') {
      alert("color is rgb(255,0,0)");

      $(element).css("color", "#000000");
      $(element).css("background-color", "#ffff00");
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<style>
  .red {
    color: rgb(255, 0, 0);
  }
</style>

<p class="red">The quick brown fox jumped over the lazy developer.</p>

Comments