When you work with colors with JavaScript you have to use the rgb-format. But when you extract colors you get back the color as a string.
So I wrote several utility Functions to manage rgb colors.
function getbg(id) {// get background color let el = document.getElementById(id) let rgb = window.getComputedStyle(el).backgroundColor return rgb } function setbg(id,rgb) {// set background color let el = document.getElementById(id) el.style.backgroundColor = rgb } function rgb2ary(rgb_str) { return rgb_str.substring(4,rgb_str.length - 1).split(/,\s*/).map(a => Number(a)) } function ary2rgb(ary){ return 'rgb(' + ary.join(',') + ')' } function rand3() { return Array.from({length:3}, (_,x) => Math.floor(Math.random() * 255)) } function rand_rgb() {return ary2rgb(rand3())}
here are some examples of how to use them :
> rand3() [251, 1, 161] > rand_rgb() 'rgb(25,120,161)' > rgb2ary(rand_rgb()) [240, 137, 194] > ary2rgb(rgb2ary(rand_rgb())) 'rgb(66,165,150)' > setbg('abc',rand_rgb()) > getbg('abc') 'rgb(78, 43, 152)'