Home >Web Front-end >CSS Tutorial >How to Get an Element's Background Color Hex Code in JavaScript?

How to Get an Element's Background Color Hex Code in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 19:01:17746browse

How to Get an Element's Background Color Hex Code in JavaScript?

Hex Code of Element Background Color

In this tutorial, we dive into a common programming challenge: obtaining the hexadecimal color code of an element's background color using JavaScript.

Example:

Consider the following HTML and CSS code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div">

Using jQuery:

Using the jQuery library, you can directly access the CSS properties of an element:

console.log($(".div").css("background-color"));

Custom JavaScript Solution:

Alternatively, you can utilize a custom JavaScript function to extract the color value in hexadecimal format:

var color = '';
$('div').click(function() {
  var x = $(this).css('backgroundColor');
  hexc(x);
  console.log(color);
})

function hexc(colorval) {
  var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  delete(parts[0]);
  for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
  }
  color = '#' + parts.join('');
}

By clicking on the element, you can retrieve the hexadecimal color code and display it in the console.

The above is the detailed content of How to Get an Element's Background Color Hex Code in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn