简体   繁体   中英

How to add a whole table by a javascript code?

I'm trying to add a table into an HTML page,using a js function.
I saw many examples for adding\\removing data from an existing table,but can't find example of adding a new table that hadn't existed before.
I am having inside my javascript variables with all the information I need for the table,now I only need to find a way to do that...lets assume my var's are v1,v2,v3,v4 and i want to creat the following table:

v1  v2
v3  v4

what is the correct code that would execute the above?

var v1 = 'v1', 
    v2 = 'v2', 
    v3 = 'v3', 
    v4 = 'v4';

var table = document.createElement('table');

var row = table.insertRow(0);
row.insertCell(0).innerHTML = v1;
row.insertCell(1).innerHTML = v2;

row = table.insertRow(1);
row.insertCell(0).innerHTML = v3;
row.insertCell(1).innerHTML = v4;

document.body.appendChild( table );

Example: http://jsfiddle.net/XPpNF/1/

var tableElem = document.createElement('table')

Lot's of answers here should work already.

BUT! Some versions of Internet Explorer can't alter the content of a <table> element once it's been created. So you can't always use tableElement.appendChild(trElement) for instance.

But you can use innerHTML to replace the html content of a table instead - that works.

Assuming you're using jQuery, that'd be something like

var awesomeTable = $("<table/>");
$("#parentElement").append(awesomeTable);

var awesomeTr = $("<tr/>");
awesomeTable.append(awesomeTr);

awesomeTr
    .append($("<td/>", {html: v1}))
    .append($("<td/>", {html: v2}))
    .append($("<td/>", {html: v3}))
    .append($("<td/>", {html: v4}));

just create the html code of your table and add it to an existing div for example:

var html = "<table";
html += "<tr><td>v1</td><td>v2</td></tr>";
html += "<tr><td>v3</td><td>v4</td></tr>";
html += "</table>";
document.getElementById('idOfYourDiv').innerHTML = html;

You can also build the table using document.createElement(table) and creating all the elements inside the table, but the first way using the string is faster.

Hope this helps

You could use jQuery to append the code you created (even if not mandatory for what you need):

var table += <table>
table += <tr> ... loop over your data variables to fill data ...
table += </tr>
table += </table>
§("# your wished table-id").html(data);

Suggestion given by Patrik is surely more elegant. This one lets you create each single tag, so that maybe zou ca directly insert extra style attributes as needed.

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