0

I'm trying to change the TR className with javascript, why it doesn't seem to work (note : must work also for IE8)

<html>
<head>
  <style>
    tr.test {background-color:#000000;margin:0;border:0;padding:0;}
  </style>
  <script>
  _table = document.getElementsByTagName("table")[0];
  _tbody = _table.getElementsByTagName("tbody")[0];
  _tr = _tbody.getElementsByTagName("tr")[0];
  _tr.className="test";
  </script>
</head>
<table>
  <tbody>
    <tr>
    <td></td>
    </tr>    
  </tbody>

</table>
</html>
user310291
  • 33,174
  • 71
  • 241
  • 439
  • place this `script` before closing`

    ` tag, or in some kind of `window load` event and it will work

    – The Process Mar 05 '16 at 22:09
  • That is quite a bit more code than you need. After you fetch the table, you can get its descendants very easily: `_table.tBodies[0].rows[0].className="test";` –  Mar 05 '16 at 22:19
  • Or use: `document.querySelector("table>tbody>tr").className="test";` –  Mar 05 '16 at 22:20

1 Answers1

1

Put your code after table tag

<html>
<head>
  <style>
    tr.test {background-color:#000000;margin:0;border:0;padding:0;}
  </style>
</head>
<body>
<table>
  <tbody>
    <tr>
    <td></td>
    </tr>    
  </tbody>

</table>
<script>
  _table = document.getElementsByTagName("table")[0];
  _tbody = _table.getElementsByTagName("tbody")[0];
  _tr = _tbody.getElementsByTagName("tr")[0];
  _tr.className="test";
</script>
</body>
</html>
Dmitriy
  • 3,607
  • 14
  • 23