Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142239

How can I add hex code to HTML element (inline style) with js

$
0
0

I have a simple class which receives an element, finds it's color in RGB, then converts it to HEX. Now this works but when I add it to the element it doesn't work Like So

import * as colorConvert from "color-convert"; // a package to convert RGB to hex
export default class Darken {
  constructor(element) {
    this.element = element;
  }

  hex() {
    const rgb = window.getComputedStyle(this.element).color;
    const exp = /\(([^)]+)\)/;
    const matches = exp.exec(rgb);
    const rgbCode = matches[1];

    const [r, g, b] = rgbCode.split(", ");

    return colorConvert.rgb.hex(r, g, b);
  }

  changeTheStylesheet() {
    const newColor = `#${this.hex()}`; // This gives me the hex code that I want #010300
    console.log(newColor); // It's as I want it in the console

    this.element.style.color = newColor; // But here it gets shown in RGB rgb(1, 3, 0)
  }
}

I want to use the hex code not the RGB Thanks


Viewing all articles
Browse latest Browse all 142239

Trending Articles