开发者

Problem while changing the background color of a table using javascript

I am trying to change the background color of a table on onchange event of a checkbox. My checkbox is inside my table. I have written a simple javascript code but I am unable to change the color of my table if any one can help me regarding this problem. Here is my code..

开发者_运维百科    function getcolor()
    {

       var color=document.getElementById("item");
        var color2=document.getElementById("item").bgColor = 'red';
        alert(color.bgColor);
        alert("its"+color2.bgColor);
    }

while my table has id='item'. Here is my checkbox code

<input type="checkbox" id='id' onchange="getcolor();"/>

Thanks.......


Try

 document.getElementById('yourId').style.backgroundColor = "Red";

Edit: This is working at my end:

<html>
    <head>
    <script type="text/javascript">
    function getcolor()
        {

            var color=document.getElementById("item");
            var color2=document.getElementById("item").style.backgroundColor = 'red';
            alert(color.style.backgroundColor);
            alert("its"+color2.style.backgroundColor);
        }
    </script>
</head>
<body>
    <pre>
        <table border="0" align="center" id="item" style=" color:#FFF;background-color:#000066">
            <th>Some Title</th>
        </table>
    </pre> 
    <input type="checkbox" id='id' onchange="getcolor();"/>
  </body>
 </html>


I believe this is your code more formatted:

function getcolor() {
    var color=document.getElementById("item");
    var color2=document.getElementById("item").bgColor = 'red';
    alert(color.bgColor);
    alert("its"+color2.bgColor);
}

As noted in the answers above, what you need is

var color2 = document.getElementById('item').style.backgroundColor = 'red';

In the second alert, color2 is a color already, so color2.bgColor (or rightly, color2.style.backgroundColor) is wrong.


The property you want is style.backgroundColor not bgColor.

function getcolor() { 
    var color=document.getElementById("item"); 
    var color2=document.getElementById("item").style.backgroundColor = 'red'; 
    alert(color.style.backgroundColor); 
    alert("its"+color2); 
}

If you want to change different table IDs, you can use the following:

function getcolor(tableID) { 
    var color=document.getElementById(tableID); 
    var color2=document.getElementById(tableID).style.backgroundColor = 'red';
    alert(color.style.backgroundColor); 
    alert("its"+color2); 
}

Then you can call it differently depending on the table ID, for example:

getcolor("item");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜