Jump to content
Sign in to follow this  
genuis

backgroundColor in if statement

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>

Share this post


Link to post
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?

Share this post


Link to post
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);

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...