Skip to content
Advertisement

getElementById not working on td elements

I am trying to access table elements with getElementById but this code is giving me “null” as the console log? Does getElementById not work with tables?

<tr>
  <td id="num1"></td>
  <td id="num2"></td>
  <td id="num3"></td>
  <td id="num4"></td>
  <td id="num5"></td>
</tr>
<script>
  console.log(document.getElementById('num3'));
</script>

Advertisement

Answer

Your HTML is invalid. While I can reproduce your problem by copy/pasting your code “as is”, it works fine if you put the <tr> and <script> elements in places they are allowed (i.e. as a child of a <table> and not as a sibling of <tr> respectively).

Use a validator to identify errors in your HTML.

<table><tr>
    <td id="num1"></td>
    <td id="num2"></td>
    <td id="num3"></td>
    <td id="num4"></td>
    <td id="num5"></td>
</tr></table>
<script>
    console.log(document.getElementById('num3'));
</script>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement