javascriptjquerydom

Add rows to an empty tbody element


I have table like this:

<table id="search-table" class="table">
  <thead>
    <tr>
      <th>Something</th>
      <th>Something2</th>
      <th>Something3</th>
      <th>Something4</th>
      <th>Something5</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

I have an API call which returns data that I want to put as row and columns in the empty tbody element.

var body = document.getElementsbyTagName("tbody");
var x = 0;

for (i = 0; i < APIcall.length; i++) {
  var createRow = body.insertRow();
  for (j = 0; j < 7; j++) {
    var x = createRow.insertCell(j);
  }
}

If I insertRow on the thead element the rows are created, but not when I try to add it to tbody. Probably me just misunderstanding something. Any suggestions what I should do?


Solution

  • you're almost there.

    First, as Rory mentioned, you're not targeting the tbody in DOM. You can fix that by replacing the first line with this:

    var body = document.querySelector('#search-table tbody')
    

    What that does, is this: It looks for an element with an ID of search-table and a descendant <tbody> and returns a reference.

    Your code would run without an error then, but I'm confused about the result. In the second line, you have var x = 0 but later on I can see var x = createRow.insertCell(j); also. (The second x would give you a reference to a new <td> element).

    Hope that helps.