jQuery Method How to - Check background color with css('background-color')








Question

We would like to know how to check background color with css('background-color').

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!-- w  w w. j  a  v  a2s . co  m-->
    $("#rect").click(function() {
        var $this = $(this);
        console.log($this.css('background-color'))
        if ($this.css('background-color') == 'rgb(255, 0, 0)') {
            $this.css('background-color', 'blue');
        }
        else {
            $this.css('background-color', 'yellow');
        }
    });
});
</script>
</head>
<body>
  <div id="rect" style="height: 100px; width: 300px; background: red">
  </div>
</body>
</html>

The code above is rendered as follows: