1

I failed to looping data with javascript and show it inside HTML table, the failed is the data that shown is not right as i expected, the data is outside the table, how to make the data show inside the table

HTML code :

  <table style="border: 1px solid">
    <thead>
      <th>Name</th>
    </thead>
    <tbody>
      <div id="demo"></div>
    </tbody>
  </table>

Javascript code :

      const cars = ["BMW", "Volvo", "Saab", "Ford"];

      let i = 0;
      let text = "";

      for (let i = 0; i < cars.length; i++) {
        text += "<tr> <td>"+ cars[i] + "</td> </tr>";
      }
      document.getElementById("demo").innerHTML = text;

The result : enter image description here

1
  • 3
    You're creating invalid HTML. Remove the div and give the same id to tbody element. Commented Jun 6, 2022 at 9:28

2 Answers 2

2

All table content should be inside cells, your div is in tbody - that's why table drop it out.

In your case - remove div and set his id to <tbody>

<table style="border: 1px solid">
   <thead>
    <th>Name</th>
   </thead>
  <tbody id="demo"></tbody>
</table>
Sign up to request clarification or add additional context in comments.

Comments

1

Just do following changes :

 <table style="border: 1px solid">
    <thead>
      <th>Name</th>
    </thead>
    <tbody id="demo"></tbody>
  </table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.