I have a simple if condition that checks the color of a element...
function changeBackgroundColor(element) {
if (element.target.style.color == "#1abc9c"){
// Do nothing
}
else { // Whatever }
But it is not working. If i use common names like "Yellow, green, etc" it works. Any tips?
style.color gives the direct color name or rgb value. It does not gives hex code. So for your case, you first need to change your hex code to rgb, then compare it with style.color So what you can do you can create a utility function
function getRgbFromHex(hexColorCode){
const hexCode = hexColorCode.startsWith('#') ? hexColorCode.substr(1) : hexColorCode;
const hexR = hexCode.substring(0,2);
const hexG = hexCode.substring(2,4);
const hexB = hexCode.substring(4,6);
return `rgb(${parseInt(hexR, 16)},${parseInt(hexG, 16)},${parseInt(hexB, 16)})`
}
and then you can change your if condition to UPDATE Removing spaces from style.color
if (element.target.style.color.replace(/\s/g,'') == getRgbFromHex("#1abc9c"))
document.getElementById('main').style.color returns a RGB value, not a HEX value.
Example:
if (document.getElementById('main').style.color == 'rgb(26, 188, 156)') {
console.log("Colour is set")
} else {
}
<div id="main" style="color: #1abc9c">
Hello, world!
</div>
<script src="test.js"></script>