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?
JavaScript
x
10
10
1
<tr>
2
<td id="num1"></td>
3
<td id="num2"></td>
4
<td id="num3"></td>
5
<td id="num4"></td>
6
<td id="num5"></td>
7
</tr>
8
<script>
9
console.log(document.getElementById('num3'));
10
</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.
JavaScript
1
10
10
1
<table><tr>
2
<td id="num1"></td>
3
<td id="num2"></td>
4
<td id="num3"></td>
5
<td id="num4"></td>
6
<td id="num5"></td>
7
</tr></table>
8
<script>
9
console.log(document.getElementById('num3'));
10
</script>