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.

1

2 Answers 2

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'];
}
Sign up to request clarification or add additional context in comments.

2 Comments

getComputedStyle() is not implemented by <=IE8, to work in IE add currentStyle to the above code.
Thanks ComFreek for your help. And Spencer Leonard too.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.