I would like to fill an HTML table with a JavaScript array
.
But, it doesn\'t work and I don\'t know why, my \"innerHTML\" is not interpreted.
My variable co
You have 3 errors in your code.
title
, link
, date
and image
on each iteration.Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table
, to solve this you may use jquery (it will create Elements
from html and append them).
Example:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '';
for( var j = 0; j < columns.length; j++ ){
//create html table cell, add class to cells to identify columns
table_html += '' + posts_array[i][j] + ' '
}
table_html += ' '
}
$( "#posts" ).append( table_html );
Another way is to use table dom api, this will not require jQuery:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table = document.getElementById('posts');
for (var i = 0; i < posts_array.length; i++)
{
var row = table.insertRow( -1 ); // -1 is insert as last
for( var j = 0; j < columns.length; j++ ){
var cell = row.insertCell( - 1 ); // -1 is insert as last
cell.className = columns[j]; //
cell.innerHTML = posts_array[i][j]
}
}