Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML : Change table color using getElementById

<HTML>
<HEAD>
</HEAD>
<BODY>
<div id="outputDiv"></div>
    <script language="JavaScript">
        document.getElementById("outputDiv").innerHTML = "";
        var HTML = "";
        HTML = "<table border=1><tr><td id='1'>1</td><td id='2'>2</td><td id='3'>3</td></tr></tabele>";
        document.getElementById("outputDiv").innerHTML = HTML;

        document.getElementById('2').innerHTML = '<td id=1 bgcolor="red">5</td>';
    </script>
</BODY>

I make table using Javascript. I want to change some cell's background color, so I use getElementById. I can change its text value, but I cannot change cell's background color. Anyone know about this problem??

like image 325
Jimmy Avatar asked Dec 21 '25 05:12

Jimmy


1 Answers

If you want to do this in Javascript without jQuery just use this :

document.getElementById('2').style.backgroundColor="red";

With the property style of an object returned with getElementById() or getElementByClass() you can change the CSS style.

Working jsfiddle

like image 61
koopajah Avatar answered Dec 22 '25 21:12

koopajah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!