Displaying a p5.Table in an HTML table outside the canvas

Hi, I wrote this function to display an p5.Table as HTML table outside the canvas for my project and I thought it might be useful to others. It might take me a while to figure out how to use git to contribute to the table object. so I ll post it here first and here is a sketch to showcase it.

https://editor.p5js.org/laurent.tran/sketches/CwwF02GX9


function build_HTML_table (tbl, tableID, parentID, classID){
  // create an HTML table with w3.css class with the table tbl
  // tbl should be a p5.Table object
  // tableID is the selector ID you want to assign to the table
  // parentID is the element ID under which you want to locate the table
  // classID is the class to add to the <table>
  
  let cc = tbl.getColumnCount();
  let rc = tbl.getRowCount();  
  let rows = tbl.getRows();
  
  print('col =' +cc + ' row = ' +rc);
  print(tbl);
  
  // setup the table header HTML string
  let hh ="<tr>"; // header html
  for (let c = 0; c < cc; c++) {
    hh +="<th>" +  tbl.columns[c] +"</th>";
  }
  hh +="</tr>"
  
  // setup the table row HTML string
  let rh =""; // row html
  
  for (let r = 0; r < rc; r++){
    rh +="<tr>";
    for (let c = 0; c < cc; c++){
      
       // add the content of each cell
       rh +="<td>" +  tbl.get(r,c) + "</td>"; 
       
    }
    rh +="</tr>";
  }
  
  //print('cell (0,1) = ' + tbl.get(0, 1));
  //print('cell (0,0) = ' + tbl.get(0, 0));
  
  let t = createElement('table', hh+rh);
  
  t.addClass(classID); // add the  table class from w3.csss
  t.id(tableID); // sets the id for this <table>
  t.parent(parentID);
  
}
2 Likes