Page 1 of 1

A style changing with Javascript question(DHTML)?

Posted: Wed Oct 01, 2008 4:05 pm
by Mds
Hi.
I have a table , Like this :

Code: Select all

<table id="MDS_Table">
  <tr>
    <td>sth</td>
    <td>sth</td>
  </tr>
  <tr>
    <td>sth</td>
    <td>sth</td>
  </tr>
  <tr>
    <td>sth</td>
    <td>sth</td>
  </tr>
</table>
Now how can I change background color of all <td> with javascript ? Image
Thank you.

Re: A style changing with Javascript question(DHTML)?

Posted: Wed Oct 01, 2008 4:26 pm
by VladSun
[js]tds = document.getElementById('MDS_Table').GetElementsByTagName('td');for (i=0; i < tds.length; i++)    tds.style.backgroundColor = 'black';[/js]

Or by playing with CSS:

Code: Select all

TABLE.yellow TD{   background-color: yellow;} TABLE.green TD{   background-color: green;}

[js]document.getElementById('MDS_Table').className = 'yellow';document.getElementById('MDS_Table').className = 'green';[/js]

Re: A style changing with Javascript question(DHTML)?

Posted: Wed Oct 01, 2008 4:45 pm
by Mds
Thanks.
I used FF3 and Firebug (FF3 plug in) and this error occurred : Image
document.getElementById("table_2").GetElementsByTagName is not a function

Re: A style changing with Javascript question(DHTML)?

Posted: Wed Oct 01, 2008 5:02 pm
by VladSun
GetElementsByTagName => getElementsByTagName

Re: A style changing with Javascript question(DHTML)?

Posted: Wed Oct 01, 2008 5:03 pm
by Mds
We must use getElementsByTagName instead of GetElementsByTagName
So my problem solved. Image
Thank you.

Code: Select all

var table = window.document.getElementById('MDS_Table').getElementsByTagName('TD');
for (i=0; i < table.length; i++)
    table[i].style.backgroundColor = '#af3830';

Re: A style changing with Javascript question(DHTML)?

Posted: Thu Oct 02, 2008 4:26 am
by VladSun
If I were you, I would use my second solution - the CSS one ;)

Re: A style changing with Javascript question(DHTML)?

Posted: Thu Oct 02, 2008 1:35 pm
by Mds
Well, Why ? Image

Re: A style changing with Javascript question(DHTML)?

Posted: Thu Oct 02, 2008 1:49 pm
by kaszu
I think because it's CSS job to do styling, not javascript.
If you need to do it dynamically, then create a CSS class and assign classname with javascript.

Re: A style changing with Javascript question(DHTML)?

Posted: Thu Oct 02, 2008 2:40 pm
by VladSun
Besause it's faster and cleaner than the JS one :) although, in fact, they are the same DOM impementation. Also, because the "code" domain and the "presentation" domain are absolutely separated.

Re: A style changing with Javascript question(DHTML)?

Posted: Thu Oct 02, 2008 3:55 pm
by Mds
Thank you Image