Tom
Tom

Reputation: 845

How to put data into HTML table using javascript

Html file:

<body>
<table id="tblUser"></table>
</body>

Javascript :

var userName="Tom";
var age= "21";
//now to put these data into a table

Now, how to put the data inside Javascript into table so that it looks like this

Name - Age
Tom    21

Upvotes: 1

Views: 1757

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You should use createElement() and appendChild(), check example bellow.

Hope this helps.


var table = document.getElementById('tblUser');
var userName="Tom";
var age= "21";

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

var td_1 = document.createElement('td');
var td_2 = document.createElement('td');

var text_1 = document.createTextNode('Name');
var text_2 = document.createTextNode('Age');

td_1.appendChild(text_1);
td_2.appendChild(text_2);
tr.appendChild(td_1);
tr.appendChild(td_2);

table.appendChild(tr);

var tr_2 = document.createElement('tr');   

var td_3 = document.createElement('td');
var td_4 = document.createElement('td');

var text_3 = document.createTextNode(userName);
var text_4 = document.createTextNode(age);

td_3.appendChild(text_3);
td_4.appendChild(text_4);
tr_2.appendChild(td_3);
tr_2.appendChild(td_4);

table.appendChild(tr_2);

document.body.appendChild(table);
<table id="tblUser" border=1></table>

Upvotes: 2

Related Questions