Can't display text on my site with my .js file

Viewed 58

I can't find why I can't write some .innerHTML to add some text on my site.

Here is a part of my HTML :

<table>
  <tr>
    <td class="test1"></td>
    <td class="test2"></td>
    <td class="test3"></td>
    <td class="test4"></td>
  </tr>
</table>

...

  </main>
  <script src="./test.js"></script>
</body>
<footer>

Here is a part of my JS :

const $test1 = document.querySelector('.test1')
$test1.innerHTML = `test`;

In this example, I want to display "text" in the first case of the first line of my table. But nothing is displayed. Maybe these 2 files are not well linked? Idk...

Hope I you have enough information, do not hesitate to ask me for more details!!!

Thanks a LOT in advance.

Have a nice day.

Here is to confirm the path is correct? enter image description here

2 Answers

You can check this small snippet here:

document.querySelector('table td.test1').innerHTML = `test`
<table>
  <tr>
    <td class="test1"></td>
    <td class="test2"></td>
    <td class="test3"></td>
    <td class="test4"></td>
</tr>
</table>

You need to wrap your html code with the <table> tag. <td> and <tr> elements have to reside within a element. You can read more about this issue here

Another issue you have is that the <td> elements are closed by the </th> tags.

 var test1 = document.querySelector(".test1");
 test1.innerHTML = 'test';
<table>
  <tr>
    <td class="test1"></td>
    <td class="test2"></td>
    <td class="test3"></td>
    <td class="test4"></td>
  </tr>
</table>

Related