How to set elements background color as hex value in JavaScript? backgroundColor
method sets only in rgb.
square.style.backgroundColor = input_color;
input_color
is #123456, but in the source sets rgb(18, 52, 86)
If you want to get the color of an element which is in rgb
format then you can convert it from rgb
to hex
format
function rgbToHex(col)
{
if(col.charAt(0)=='r')
{
col=col.replace('rgb(','').replace(')','').split(',');
var r=parseInt(col[0], 10).toString(16);
var g=parseInt(col[1], 10).toString(16);
var b=parseInt(col[2], 10).toString(16);
r=r.length==1?'0'+r:r; g=g.length==1?'0'+g:g; b=b.length==1?'0'+b:b;
var colHex='#'+r+g+b;
return colHex;
}
}
Call the function
var col=document.getElementById('myDiv').style.backgroundColor;
alert(rgbToHex(col)); // alerts hex value
Here is an example.
A better solution to your problem would be just to set the background color like this
square.style.backgroundColor = "rgb(12,34,56)";
Otherwise I would use Sheika's example
Found something that should work:
document.getElementById('square').attributes['style'].textContent='background-color:'+ input_color
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With