0

Could anybody tell me how I can create this table using my function below?

<tbody>
 <tr>
  <td><h3>Main1</h3></td>
  <td>
    <h5>
      text1
    </h5>
  </td>
  <td>
    <h5>
     text2
    </h5>
  </td>
 </tr>
 <tr>
   <td><h3>Main2</h3></td>
   <td>
    <h5>
      text3
    </h5>
   </td>
   <td>
    <h5>
      text4
    </h5>
   </td>
 </tr>
</tbody>

Here are my data and my functions. I can only create a table without the inner h3, h5 tags with it.

data =[['Main1', 'text1', 'text2'],['Main2', 'text3', 'text4']]

  var table = document.getElementsByTagName("tbody")[0];
      table.innerHTML = ""; 
      for (var i = 0; i < data.length; i++) {
        var child = data[i];
        var row = table.insertRow();
        Object.keys(child).forEach(function (k) {
          var cell = row.insertCell();
          cell.appendChild(document.createTextNode(child[k]));
road
  • 479
  • 3
  • 20
  • `document.getElementsByTagName("tbody")[0]` <-- [No, no, no, no, no!](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) You also don't need `createTextNode()` and instead can just set the `textContent` of the cell. Lastly, heading elements define sections of a document. A table column is not really a section, per se and is the reason we have the `th` element. Are you really sure you need headings here? And, if you are, a heading number should be based on the heading that was in effect prior to it... – Scott Marcus Oct 05 '20 at 16:54
  • ...So an `h5` would be a sub-section of an `h4` and so on. If you are just using headings because of the way the browser styles the text, you're not using them correctly. – Scott Marcus Oct 05 '20 at 16:55

1 Answers1

1

Try using javascript string interpolation:

data =[['Main1', 'text1', 'text2'],['Main2', 'text3', 'text4']]
var table = document.getElementsByTagName("tbody")[0];
      table.innerHTML = ""; 
      for (var i = 0; i < data.length; i++) {
        var row = table.insertRow();
        row.innerHTML = `<tr><td><h3>${data[i][0]}</h3></td><td>${data[i][1]}</td><td>${data[i][2]}</td></tr>`;
        
        }
<table>
<tbody>
  
</tbody>
</table>

But this attitude is quite obsolete, I strongly recomend using modern binding frameworks like Vue

kavanka
  • 133
  • 8