1

I have a Javascript array that contains a string which is in the format <td>200</td><td>I3</td><td>NAME NAME</td><td>EXTRA</td>

Example Array[0] contains <td>200</td><td>I3</td><td>NAME NAME</td><td>EXTRA</td>
which is a string (and so on)

How do I print a html table while iterating through the array?

3 Answers 3

3

You could use this:

var html = '<table><tr>' + myarray.join('</tr><tr>') + '</tr></table>';

For example:

myarray = [
    '<td>200</td><td>I3</td><td>NAME NAME</td><td>EXTRA</td>',
    '<td>150</td><td>I1</td><td>Some data</td><td>-999</td>',
    '<td>360</td><td>K9</td><td>other data</td><td>nothing</td>',
];

var html = '<table border=1><tr>' + myarray.join('</tr><tr>') + '</tr></table>';

document.querySelector('#mytablemustcomehere').innerHTML = html;
<div id="mytablemustcomehere"></div>

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

4 Comments

and I can use document.write(html) to print the entire table?
Yes, I added that just now.
Except document.write is a big code smell. Better to use innerHTML.
Indeed, this is just for demo. Be careful with document.write. It is better to locate where you want to insert it, and then assign to innerHTML. I have updated my snippet to do just that.
2

You can loop through your array elements and add <tr> to them for each row.

var arr = ["<td>200</td><td>I3</td><td>NAME NAME 1</td><td>EXTRA 1</td>", 
           "<td>100</td><td>I2</td><td>NAME NAME 2</td><td>EXTRA 2</td>"];

var str = "";

var table = document.getElementById("myTable");

for(var i = 0; i < arr.length; i++) str += "<tr>"+arr[i]+"</tr>";

table.innerHTML = str;
<table id="myTable"></table>

Comments

2

@trincot's answer is best for the specific question. I'd like to expand a little on how to do this using the DOM API instead.

function createRowHTML(itemData) {
  return '<tr><td>' + itemData.join('</td><td>') + '</td></tr>';
}

function appendTableTo(element, items) {
  var table = document.createElement('table');
  table.innerHTML = items.map(createRowHTML).join('');
  element.appendChild(table);
}

var items = [
  [200, 'I3', 'NAME NAME 1', 'EXTRA 1'], 
  [100, 'I2', 'NAME NAME 2', 'EXTRA 2']
];

appendTableTo(document.querySelector('body'), items);

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.