Question

How to write an IF condition in purely JavaScript to check if background color of <li> tag is equal to particular RGBA color combination.

For example:

if(document.getElementById('element').style.backgroundColor == "rgba(213,212,212,0.5)")
{
     alert("MATCHED");
}
else
{
     alert("FAILED");
}

But this comparison for IF statement does NOT work! Please help!

Was it helpful?

Solution

The CSS value is returned in a particular way.

Try comparing it to: "rgba(213, 212, 212, 0.5)"

(spaces after each comma).

Since JavaScript's rounding errors are the worst, and you really don't care about the alpha, you can just cut out the part you need:

var color = document.getElementById('element').style.backgroundColor;
color = color.substring(
                          color.indexOf('(') + 1,
                          color.lastIndexOf(color[3] == 'a' ? ',' : ')')
                        );

if (color == '213, 212, 212')
{
    alert("MATCHED");
}
else
{
    alert("FAILED");
}

Works whether or not it's rgb or rgba

If the background-color is not defined as an inline-style, you might want to use:

var color = window.getComputedStyle(document.getElementById('element')).backgroundColor;

instead (of the first line in code).

OTHER TIPS

Check

window.getComputedStyle(document.getElementById('element')).backgroundColor

instead of

document.getElementById('element').style.backgroundColor

so your new code would be:

if(window.getComputedStyle(document.getElementById('element')).backgroundColor === "rgba(213,212,212,0.5)")
{
     alert("MATCHED");
}
else
{
     alert("FAILED");
}

(As you can see, I'm checking with three equal signs because no conversion is necessary.)

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top