简体   繁体   中英

Populate HTML Table from javascript array format

Suppose i have an java script Array in the following format,

[
"Heading 1",
"Heading 2",
"Data 1",
"Data 2",
"Data 3",
"Data 4",
 ]

I need to make a HTML table from the array in the following format 在此处输入图片说明

I've never dynamically created an HTML Table from Javascript. Can anyone help me out?
Thanks in advance!

Here you can find some code to make what you need to:

 //set the number of columns (we use 2 because you have 2 "Heading") var _numberCol = 2, _arr = [ "Heading 1", "Heading 2", "Data 1", "Data 2", "Data 3", "Data 4" ]; //create a table var $table = document.createElement("table"), $row; for(var _k = 0; _k < _arr.length; _k++){ //we create a row when index is divisible for _numberCol if(_k % _numberCol===0) $row = $table.insertRow(-1); //for each element inside the array we crate a cell inside the current row $col = $row.insertCell(-1); //then we put the value inside like text $col.innerText = _arr[_k]; } //now we can append our table where we need to place it document.body.appendChild($table); 

This code works only with your type of array that has only one dimension, and all Heading are defined like each other cell in the table.

If you need it in JS you can use the array to create an html string for the table. If you then need to put it inside an element in your html page you could do something like:

document.getElementById("myDiv").innerHTML = myHtmlTable;

I wrote an example of a function to generate such a string in this JSfiddle .

(Let me know if you can't access the fiddle, I've never used it before for StackOverflow answers).

 var data = [ "Heading 1", "Heading 2", "Data 1", "Data 2", "Data 3", "Data 4", ] var tabdiv = document.createElement('div'); tabdiv.setAttribute("id", "tab"); document.body.appendChild(tabdiv) document.getElementById("tab").innerHTML = "<table border = '1' style='border-collapse: collapse;'>" +'<tr>' + '<th>'+ data[0] + "</th>" + '<th>'+ data[1] + "</th>" + '</tr>' + '<tr>' + '<td>' + data[2] + '</td>' + '<td>' + data[3] + '</td>' + '</tr>' + '<td>' + data[4] + '</td>' + '<td>' + data[5] + '</td>' + '</tr>'; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM