0

Well, I have a function to get the background color of a clicked html element. however, as I set the background color via css, with a class, the object`s background color in x.style.background just returns "";

My code: Html:

<li onclick="setCor(this)" id="vermelho" class="vermelho">Vermelho</li>

The JS function:

function setCor(x){
    cor = x.style.backgroundColor;
}

And the .vermelho class:

.vermelho{
    background-color: #ff0000;
}

How can I get the css value via JS? I can't use jQuery for it, need to be just JS.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Kio Coan
  • 561
  • 2
  • 7
  • 24
  • possible duplicate of [How to get a style attribute from a css class by javascript/jquery?](http://stackoverflow.com/questions/16965515/how-to-get-a-style-attribute-from-a-css-class-by-javascript-jquery) – web_bod Oct 28 '13 at 17:58

2 Answers2

4

element.style only returns the inline style attributes (see here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style#Notes)

You might be better off using window.getComputedStyle(). That however returns an RGB color which you might want to convert to hex if you desire.

function setCor(x) {
  cor = window.getComputedStyle(x, null)['background-color'];
}
ComFreek
  • 29,044
  • 18
  • 104
  • 156
lxe
  • 7,051
  • 2
  • 20
  • 32
0

Just to add a note at the @Ixe answer's.

You may want to use this function to convert the value from RGB to HEX:

Javascript

function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); }

Example

function toHex(value) { return "#" + hex(value[0]) + hex(value[1]) + hex(value[2]) }

Code taken from this guy Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

Community
  • 1
  • 1
Felipe Miosso
  • 7,309
  • 6
  • 44
  • 55