1

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
1

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.