0

I found a few other posts that seem to address this using jquery, but I would like to use javascript only. I would like to create a table using bootstrap but can't seem to figure out how to append new data to the table. It is creating the header, but then just dumping the items I want as rows below the table header.

html

<div id = specificFailureCountTable-js></div>

js

let filterText = 'machines';
let tableData = document.getElementById("specificFailureCountTable-js"); 
let data = [["machineA",15],["machineB",54],["machineC",26]];

//set header of table
tableData.innerHTML = `
<table class="table table-striped" id = "myTable">
  <thead>
    <tr>
      <th scope="col">${filterText}</th>
      <th scope="col">Count</th>
    </tr>
  </thead>
  <tbody>
  `;
  //create//append rows
for(i = 0; i < data.length; i++){
    tableData.innerHTML = tableData.innerHTML +
    `<tr>
      <th scope="row">${i}</th>
      <td>${data[i][0]}</td>
      <td>${data[i][1]}</td>
    </tr>`
}
//close off table
tableData.innerHTML = tableData.innerHTML +
  `</tbody>
  </table>`
  ;
2
  • You need to create single string and after the loop assign to the innerHTML otherwise you will have broken DOM structure. You can check what you've got as DOM output if you inspect the DOM using dev tools (in Chrome right click -> context menu -> inspect element or F12). Commented Feb 16, 2019 at 18:03
  • If I create single string within for loop it want's to create as many tables as there are data.[i] objects. That's why I figured I had to break it up into multiple strings. Commented Feb 16, 2019 at 18:09

1 Answer 1

1

Just use variable that will define your table append to that variable and at the end when it would be ready assign to to tableData.innerHTML, otherwise you will have broken DOM (not sure what the output would be but it maybe different depending on browser):

let filterText = 'machines';
let tableData = document.getElementById("specificFailureCountTable-js"); 
let data = [["machineA",15],["machineB",54],["machineC",26]];

//set header of table
let table = `
<table class="table table-striped" id = "myTable">
  <thead>
    <tr>
      <th scope="col">${filterText}</th>
      <th scope="col">Count</th>
    </tr>
  </thead>
  <tbody>
  `;
  //create//append rows
for(i = 0; i < data.length; i++){
    table = table +
    `<tr>
      <th scope="row">${i}</th>
      <td>${data[i][0]}</td>
      <td>${data[i][1]}</td>
    </tr>`
}
//close off table
table = table +
  `</tbody>
  </table>`
  ;

tableData.innerHTML = table;

And one side note: you can use table += 'xxx' as shortcut for table = table + 'xxx'

Sign up to request clarification or add additional context in comments.

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.