Jump to content

backgroundColor in if statement


genuis

Recommended Posts

I cannot get my if statement to work?  I am trying to compare the background color of a table cell within an if statement (i.e. I cannot get the false to work here):

<!DOCTYPE html>
<html>
<body>

 <table id="tbl" border="1">
        <tr>
            <td>ONE</td>
            <td>TWO</td>
            <td>THREE</td>
        </tr>
        <tr>
            <td>FOUR</td>
            <td style="background-color:yellow" onclick="changeColor()">FIVE</td>
            <td>SIX</td>
        </tr>
        <tr>
            <td>SEVEN</td>
            <td>EIGHT</td>
            <td>NINE</td>
        </tr>
    </table>
    <script type="text/javascript">
    
    function changeColor() {  
    
        if (tbl.rows[1].cells[1].style.background = '#00f') {
              alert("true")
        } else {
              alert("false")
           }
        }
    </script>

</body>
</html>

Link to comment
Share on other sites

Oh! I tried looking at this quite in depth. Prepared an answer, wanted to think on it  a bit more, because that should be false. Went and got a coffee. And now:

 

You're using a single = (assignment) instead of the == (loose equality) or even === (strict equality). Do you find that when you run it, it actually turns the cell blue?

Link to comment
Share on other sites

Browsers transform colors from the style attribute. I think Firefox tends to represent them in rgb() format. You also will have to use backgroundColor instead of just background because that's the property being used by the element.

For the purpose of debugging, try printing out the value to see what it has:

alert(tbl.rows[1].cells[1].style.backgroundColor);

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...