I'm trying to do a conversion from rgb to hex using a variable.
Instead of the last line I want
var rgbnhcp1 = rgbToHex(nhcp1)
And later use it to write in a div
document.getElementById("TextWithRgbValue").innerHTML = rgbnhcp1;
The problem is that you have to put ready value in the code above, like rgb 20,45,233 and not a variable to later use it to put it in a div. Could you help?
// Variables - taking color property in rgb from css classes
var nhcp1 = window.getComputedStyle(document.querySelector(".nhcp1"), null).getPropertyValue('background-color');
var nhcp2 = window.getComputedStyle(document.querySelector(".nhcp2"), null).getPropertyValue('background-color');
var nhcp3 = window.getComputedStyle(document.querySelector(".nhcp3"), null).getPropertyValue('background-color');
var nhcp4 = window.getComputedStyle(document.querySelector(".nhcp4"), null).getPropertyValue('background-color');
var nhcp5 = window.getComputedStyle(document.querySelector(".nhcp5"), null).getPropertyValue('background-color');
// RGB to HEX
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
console.log(rgbToHex(0, 51, 255)); // #0033ff
.nhcp4 { bakground-color:teal}
.nhcp5 { bakground-color:yellow}
<div class="nhcp1" style="background-color:red">Div 1</div>
<div class="nhcp2" style="background-color:blue">Div 2</div>
<div class="nhcp3" style="background-color:green">Div 3</div>
<div class="nhcp4">Div 4</div>
<div class="nhcp5">Div 5</div>