Get Element Background Color Using jQuery

Retrieving the background color of an HTML element is a common task in web development, often used for dynamic styling, theming, or validation. This guide demonstrates how to extract an element's background color using jQuery's built-in .css() method, explains the format of the returned data, and covers how to handle color format conversions.

Using the .css() Method

The primary and most straightforward way to retrieve CSS properties in jQuery is by using the .css() method. To get the background color, pass 'background-color' or 'backgroundColor' as an argument to the method.

// Select the element by ID, class, or tag, then call .css()
var bgColor = $('#myElement').css('background-color');

console.log(bgColor);

Understanding the Return Value

Even if you defined the color in your stylesheet as a HEX code (#ffffff) or a named color (white), browsers typically compute and return the value as an rgb() or rgba() string.

For example:

  • A black background will return "rgb(0, 0, 0)".
  • A semi-transparent black background will return "rgba(0, 0, 0, 0.5)".
  • An element with no background color set will usually return "rgba(0, 0, 0, 0)" or "transparent", representing default transparency.

Complete Working Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery Background Color Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #box {
      width: 100px;
      height: 100px;
      background-color: #3498db;
    }
  </style>
</head>
<body>

  <div id="box"></div>
  <button id="checkColor">Get Color</button>

  <script>
    $('#checkColor').on('click', function() {
      var color = $('#box').css('background-color');
      alert('The background color is: ' + color); 
      // Output: "The background color is: rgb(52, 152, 219)"
    });
  </script>

</body>
</html>

Converting RGB to HEX

If your application requires the color code in hexadecimal format rather than RGB, you can convert the output string using a simple JavaScript helper function:

function rgbToHex(rgb) {
  var result = rgb.match(/\d+/g);
  if (!result || result.length < 3) return rgb;

  return "#" + result.slice(0, 3).map(function(val) {
    return ("0" + parseInt(val).toString(16)).slice(-2);
  }).join("");
}

var rgbColor = $('#box').css('background-color');
var hexColor = rgbToHex(rgbColor);

console.log(hexColor); // Outputs: "#3498db"