Home >Web Front-end >CSS Tutorial >How Can I Extract Hexadecimal Background Color Codes from HTML Elements?
Retrieving the hexadecimal color code of an element's background by accessing its Cascading Style Sheet (CSS) stylesheet.
There are several methods to accomplish this task:
Method 1: Using JavaScript with jQuery:
console.log($(".div").css("background-color"));
See example in code snippet:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="div">
Method 2: Using JavaScript with pure DOM methods:
var color = document.querySelector(".div").style.backgroundColor;
Method 3: Using a color picker tool:
Alternatively, you can employ a color picker tool, such as the one provided in the following example, to visually select and acquire the desired color code:
<div class='div'>
JavaScript code for converting RGB to hex:
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(''); }
The above is the detailed content of How Can I Extract Hexadecimal Background Color Codes from HTML Elements?. For more information, please follow other related articles on the PHP Chinese website!